Java中最简单的就是用Date来显示时间日期。列:
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);//显示时间日期
}
以上就是Java中最简单的显示时间日期的方法。
我们还可以利用SimpleDateFormat函数自定义一下时间日期的显示格式:
SimpleDateFormat函数语法:
G 年代标志符
y 年
M 月
d 日
h 时 在上午或下午 (1~12)
H 时 在一天中 (0~23)
m 分
s 秒
S 毫秒
E 星期
D 一年中的第几天
F 一月中第几个星期几
w 一年中第几个星期
W 一月中第几个星期
a 上午 / 下午 标记符
k 时 在一天中 (1~24)
K 时 在上午或下午 (0~11)
z 时区
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat f = new SimpleDateFormat("yyy-MM-dd-EE");//定义时间的格式
System.out.println(f.format(date));//用定义好的格式显示日期时间
}
还可以让日期的显示变成中文的
使用DateFormat类获取系统的当前时间的示例如下所示:
SHORT 模式的日期为:12-2-17 下午7:43
MEDIUM 模式的日期为:2012-2-17 19:43:39
LONG 模式的日期为:2012年2月17日 下午07时43分39秒
FULL 模式的日期为:2012年2月17日 星期五 下午07时43分39秒 CST
public static void main(String[] args) {
Date date = new Date();
DateFormat shortDateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
DateFormat mediumDateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
DateFormat longDateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
DateFormat fullDateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
System.out.println("SHORT 模式的日期为:" + shortDateFormat.format(date));
System.out.println("MEDIUM 模式的日期为:" + mediumDateFormat.format(date));
System.out.println("LONG 模式的日期为:" + longDateFormat.format(date));
System.out.println("FULL 模式的日期为:" + fullDateFormat.format(date));
}
扫描二维码关注公众号,回复:
2237383 查看本文章
这样我们就能输出自己想要的日期格式了