String的几种常见格式化

一、日期格式化

常用的日期格式化转换符

%te:一月中的某一天(1-31)  2

%tb:指定语言环境的月份简称  Feb或二月

%tB:指定语言环境的月份全称  February或二月

%tA:指定语言环境的星期几全称 Monday、星期一

%ta:指定语言环境的星期几简称 Mon、星期一

%tc: 包括全部日期和时间信息

%tY:4位年份  2023

%tj: 一年中的第几天(001-366)  085

%tm: 月份 03

%td: 一个月中的第几天(01-31) 02

%ty: 2位年份 23

代码示例如下:

import java.util.Date;

/**
 * @author qx
 * @date 2023/06/10
 * @desc String.format学习
 */
public class StringTest {
    public static void main(String[] args) {
        Date date = new Date();
        // 输出 2023
        System.out.println(String.format("%tY", date));
        // 输出 六月
        System.out.println(String.format("%tB", date));
        // 输出 星期六
        System.out.println(String.format("%tA", date));
        // 输出 06
        System.out.println(String.format("%tm", date));

    }
}

二、时间格式化

%tH:2位数字的24小时制的小时(00-23) 14

%tI:2位数字的12小时制的小时(01-12) 10

%tK : 2位数字的24小时制的小时(0-23) 5

%ti: 2位数字的12小时制的小时(1-12) 10

%tM:2位数字的分钟数(00-59) 05

%tS: 2位数字的秒数(00-60) 12

%tZ: 时区缩写形式的字符串 CST

代码示例如下:

import java.util.Date;

/**
 * @author qx
 * @date 2023/06/10
 * @desc String.format学习
 */
public class StringTest {
    public static void main(String[] args) {
        Date date = new Date();
        String hour = String.format("%tH", date);
        String minute = String.format("%tM", date);
        String second = String.format("%tS", date);
        // 输出 现在是:15时35分33秒
        System.out.println("现在是:" + hour + "时" + minute + "分" + second + "秒");
    }
}

三、常见日期时间格式化

%tF: 年-月-日 格式(4位年份) 2023-06-10

%tD: 月/日/年格式(2位年份) 10/06/23

%tc: 全部日期和时间信息

%tT: 时:分:秒(24时制)  15:38:20

%tR: 时:分格式(24时制) 15:25

代码示例如下:

import java.util.Date;

/**
 * @author qx
 * @date 2023/06/10
 * @desc String.format学习
 */
public class StringTest {
    public static void main(String[] args) {
        Date date = new Date();
        // 输出 2023-06-10
        System.out.println(String.format("%tF", date));
        // 输出 15:39:50
        System.out.println(String.format("%tT", date));
    }
}

四、常规类型格式化

%s、%S: 结果被格式化成字符串类型

%d: 结果被格式化为十进制整数

%n:结果为特定于平台的行分隔符

%b、%B: 结果被格式化位布尔类型

代码示例如下:

/**
 * @author qx
 * @date 2023/06/10
 * @desc String.format学习
 */
public class StringTest {
    public static void main(String[] args) {
        System.out.println(String.format("%d", 20 / 2));
        System.out.println(String.format("%b", 3 > 2));
        System.out.println(String.format("hello %s", "world"));
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qinxun2008081

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值