Java中Date、Calendar、LocalDate、LocalTime、LocalDateTime时间类的格式化及时间戳的转换

目录

一、利用格式化符号进行格式化

二、利用格式化工具进行格式化

三、时间戳转换


一、利用格式化符号进行格式化

        1、格式化符号

转换符说明结果
%tH小时(00~23)15
%tI小时(01~12)03
%tk小时(00~23)15

%tI

小时(1~12)3
%tM分钟(00~5935
%tS秒(00~59)55
%tL毫秒(000~999)923
%tN9位数微秒(000000000~999999999)923000000
%tp当前语言环境上午/下午下午
%tz时区+08:00
%tZ时区CST
%ts从1970-01-01 00:00:00到现在的秒1526196955
%tQ从1970-01-01 00:00:00到现在的毫秒1526196955932
%tF年-月-日2018-03-13
%tD月/日/年05/13/18
%tc全部时间日期星期日 五月 13 15:44:21 CST 2018
%tr时分秒PM03:44:21 下午
%tT时分秒15:44:21
%tR时分15:44
%tA星期几星期四
%ta周几周四
%tB几月六月
%tb几月6月

         以上格式化符号对Date、Calendar、LocalDate、LocalTime、LocalDateTime及时间戳均能进行格式化。但不能对LocalDate类进行含有时分秒的进行格式化,因为在LocalDate中只能精确到年月日对时分秒没有进行处理的能力;同样的不能对LocalTime进行含有年月日的格式化符号进行格式化。

部分演示:

//获取当前时间
LocalDateTime now = LocalDateTime.now();
//格式化输出
System.out.printf("%tF %<tT %<tA %<tB %<tp%n",now);

//格式化为字符串
String str = String.format("%tF %<tT %<tA %<tB %<tp",now);
System.out.println(str);

        注:以上代码中“<”代表要格式化的对象和前一个一致,%n为格式化输出中的换行。

运行结果:

二、利用格式化工具进行格式化

1、格式化符号

字母日期或时间元素表示示例
GEra标志符TextAD
yYear1996;96
M年中的月份MonthJuly;Jul;07
w年中的周数Number27
W月份中的周数Number2
D年中的天数Number189
d月份中的天数Number10
E星期中的天数TextTuesday,Tue
a上下午TextPM
H一天中的小时数(0-23)Number0
k一天中的小时数(1-24)Number24
Kam/pm中的小时数(0-11)Number0
ham/pm中的小时数(1-12)Number12
m小时中的分钟数Number30
s分钟中的秒数Number55
S豪秒数Number978
z时区General time zonePacific St andard Time;PST;GMT-08Z
Z时区RFC 822 time zone-80:00
        DateTimeFormatter . ofPattern (),格式化工具只能格式化LocalDate、LocalTime、LocalDateTime和时间戳,对于老的时间类Date、Calendar是无法进行格式化的。
 //设定格式化工具要格式化的内容
 DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EEEE MMMM a");
 
 //LocalDate LocalTime LocalDateTime 时间戳均可
 LocalDateTime now = LocalDateTime.now();

 //以下两种格式化方式都是可以的
 System.out.println(now.format(df));
 System.out.println(df.format(now));

运行结果:

三、时间戳转换

//获取当前时间的Date对象
Date date = new Date();
//利用getTime()方法获取时间戳
long l1 = date.getTime();

//获取当前时间的Calendar对象
Calendar cl = Calendar.getInstance();
//获取Date类型的对象
Date dc = cl.getTime();
//将Date类型对象转化为时间戳
long l2 = dc.getTime();

//获取当前时间的LocalDateTime对象
LocalDateTime ldt = LocalDateTime.now();
//将ldt对象转化为时间戳
long l3 = ldt.toInstant(ZoneOffset.of("+08:00")).toEpochMilli();

//分别输出时间戳
System.out.println(l1);
System.out.println(l2);
System.out.println(l3);

运行结果:

         值得注意的是Calendar类不能直接转换为时间戳,只能先转换为Date类型再利用Date类的方法进行转换。而LocalDateTime转换为时间戳的方式更为麻烦,因为LocalDateTime类中的方法已经足够我们使用了没必要转换为时间戳再去使用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值