栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Java中获取当前时刻的年,月,日,小时,分钟,秒和毫秒?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Java中获取当前时刻的年,月,日,小时,分钟,秒和毫秒?

您可以

java.time.LocalDateTime
为此使用吸气剂。

LocalDateTime now = LocalDateTime.now();int year = now.getYear();int month = now.getMonthValue();int day = now.getDayOfMonth();int hour = now.getHour();int minute = now.getMinute();int second = now.getSecond();int millis = now.get(ChronoField.MILLI_OF_SECOND); // Note: no direct getter available.System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);

或者,当您尚未使用Java
8时,请使用

java.util.Calendar

Calendar now = Calendar.getInstance();int year = now.get(Calendar.YEAR);int month = now.get(Calendar.MONTH) + 1; // Note: zero based!int day = now.get(Calendar.DAY_OF_MONTH);int hour = now.get(Calendar.HOUR_OF_DAY);int minute = now.get(Calendar.MINUTE);int second = now.get(Calendar.SECOND);int millis = now.get(Calendar.MILLISECOND);System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);

不管哪种方式,到目前为止都将打印:

2010-04-16 15:15:17.816

要转换

int
String
,请使用
String#valueOf()


如果您的意图 毕竟
是以一种人类友好的字符串格式来排列和显示它们,那么最好使用Java8的

java.time.format.DateTimeFormatter
(此处的教程),

LocalDateTime now = LocalDateTime.now();String format1 = now.format(DateTimeFormatter.ISO_DATE_TIME);String format2 = now.atZone(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME);String format3 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.ENGLISH));System.out.println(format1);System.out.println(format2);System.out.println(format3);

或者,如果您尚未使用Java
8,请使用

java.text.SimpleDateFormat

Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now);String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now);String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now);System.out.println(format1);System.out.println(format2);System.out.println(format3);

无论哪种方式,都会产生:

2010-04-16T15:15:17.8162010年4月16日,星期五,格林尼治标准时间15:15:1720100416151517


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/486139.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号