在程序设计中,经常需要显示时间和日期。如果想输出满意的日期和时间格式,一般需要编写大量的代码经过各种算法才能实现。format()方法通过给定的特殊转换符作为参数来实现对日期和时间的格式化。
转 换 符 | 说 明 | 示 例 |
---|---|---|
%te |
一个月中的某一天(1~31) |
2 |
%tb |
指定语言环境的月份简称 |
Feb(英文)、二月(中文) |
%tB |
指定语言环境的月份全称 |
February(英文)、二月(中文) |
%tA |
指定语言环境的星期几全称 |
Monday(英文)、星期一(中文) |
%ta |
指定语言环境的星期几简称 |
Mon(英文)、星期一(中文) |
%tc |
包括全部日期和时间信息 |
星期二 三月 25 13:27:22 CST 2018 |
%tY |
4位年份 |
2018 |
%tj |
一年中的第几天(001~366) |
085 |
%tm |
月份 |
03 |
%td |
一个月中的第几天(01~31) |
02 |
%ty |
2位年份 |
18 |
具体应用方法,如下示例:
import java.util.Date;
public class Demo15 {
public static void main(String[] args) {
Date date=new Date();
String year=String.format("%tY",date);
String month=String.format("%tB",date);
String day=String.format("%td",date);
String date2=String.format("%tc",date);
System.out.println("完整日期是:"+date2);
System.out.println("今年是"+year+"年");
System.out.println("现在是"+month);
System.out.println("今天是"+day+"号");
}
}
运行结果
转 换 符 | 说 明 | 示 例 |
---|---|---|
%tH |
2位数字的24小时制的小时(00~23) |
14 |
%tI |
2位数字的12小时制的小时(01~12) |
05 |
%tk |
2位数字的24小时制的小时(0~23) |
5 |
%tl |
2位数字的12小时制的小时(1~12) |
10 |
%tM |
2位数字的分钟(00~59) |
05 |
%tS |
2位数字的秒数(00~60) |
12 |
%tL |
3位数字的毫秒数(000~999) |
920 |
%tN |
9位数字的微秒数(000000000~999999999) |
062000000 |
%tp |
指定语言环境下上午或下午标记 |
下午(中文)、pm(英文) |
%tz |
相对于GMT RFC 82 格式的数字时区偏移量 |
+0800 |
%tZ |
时区缩写形式的字符串 |
CST |
%ts |
1970-01-01 00:00:00 至现在经过的秒数 |
1206426646 |
%tQ |
1970-01-01 00:00:00 至现在经过的毫秒数 |
1206426645453 |
具体应用如下示例:
import java.util.Date;
public class Demo16 {
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);
String time=String.format("%tQ",date);
System.out.println("现在是"+hour+"时"+minute+"分"+second+"秒");
System.out.println("1970-01-01 00:00:00 至现在经过"+time+"毫秒");
}
}
运行结果
转 换 符 | 说 明 | 示 例 |
---|---|---|
%tF |
“年-月-日”格式(4位年份) |
2018-9-18 |
%tD |
“月/日/年”格式(2位年份) |
09/18/18 |
%tc |
全部日期和时间信息 |
星期二 三月 25 15:20:00 CST 2018 |
%tr |
“时:分:秒 PM(AM)”格式(12时制) |
03:22:06 下午 |
%tT |
“时:分:秒”格式(24时制) |
15:23:50 |
%tR |
“时:分:秒”格式(24时制) |
15:25 |
具体应用如下:
import java.util.Date;
public class Demo17 {
public static void main(String[] args) {
Date date=new Date();
String time=String.format("%tc",date);
String form=String.format("%tF",date);
System.out.println("全部的时间信息是:"+time);
System.out.println("年-月-日格式:"+form);
}
}
运行结果
(以上内容仅供参考)