Java中的格式化

本文介绍了使用Java进行日期和时间的格式化操作,包括如何获取当前时间戳、计算指定天数前的日期,以及利用日历类获取时间戳的方法。此外,还详细讲解了数字格式化的多种方式,如百分比显示、货币格式化等,并展示了字符串格式化的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.格式化时间日期

public static void main(String[] args) {
        //时间戳(long类型的数字)
        System.out.println(System.currentTimeMillis());//打印当前时间戳
        long time = System.currentTimeMillis();//系统时间戳
        System.out.printf("%tF %<tT%n",time);//tF代表年月日 Tt代表时分秒 %n是换行
        //格式化输出用 System.out.printf();

        //用时间戳计算两天前的日期
        long time2 = System.currentTimeMillis() - (1000*60*60*24*2);//当前时间戳 - 两天的时间
        System.out.printf("%tF %<tT%n",time2);//格式化输出两天前的时间戳

        System.out.println("-----------------");
        //日历类获取时间戳
        Calendar time3 = Calendar.getInstance();//实例类格式化
        int year = time3.get(Calendar.YEAR);//获取当前年份
        System.out.println(year);//打印输出
        long time4 = time3.getTimeInMillis();//日历获取当前时间戳
        System.out.println(time4);//打印输出
    }

2.格式化数字

public static void main(String[] args) {
        //数字格式化
        //数字百分比显示
        NumberFormat a = NumberFormat.getPercentInstance();//获取数字百分比
        System.out.println(a.format(.3));//30%
        System.out.println(a.format(.47586));//保留两位小数进一 48%

        //格式化货币
        NumberFormat b = NumberFormat.getCurrencyInstance();//活动货币实例
        b.setMinimumFractionDigits(3);//设置最小分数位数
        System.out.println(b.format(1000234));//¥1,000,234.000

        //DecimalFormat 是NumberFormat的子类,
        DecimalFormatSymbols fs = new DecimalFormatSymbols();
        fs.setGroupingSeparator(',');
        DecimalFormat df = new DecimalFormat("#,###.00",fs);
        //df.setMinimumFractionDigits(2);
        df.setPositivePrefix("¥");
        System.out.println(df.format(23422343.1954));//¥23,422,343.20
        
    }

3.格式化字符串

public static void main(String[] args) {
        //字符串格式化
        String name = "张三";
        int age = 18;
        int id = 1020;
        //%s s 代表String字符串  %d d代表10进制整数
        System.out.printf("名字:%s 年龄:%d 身份:%d%n",name,age,id);

        //格式化字符串 左对齐 右对齐 大写显示 小写显示
        System.out.println();
        System.out.printf("%n");
        // - 代表左对齐
        System.out.printf("%-10s%-6d%n","张三",18);
        // + 代表右对齐
        System.out.printf("%10s%6d%n","李四",18);
        //大写S输出大写HELLOWORLD
        //小写s输出小写helloworld
        System.out.printf("%S %<s%n","helloworld");
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值