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

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

如何在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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5478278.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存