当前位置: 首页 > 面试题库 >

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

东郭鹤龄
2023-03-14
问题内容

如何在Java中获取当前时刻的年,月,日,时,分,秒和毫秒?我想把它们当作Strings


问题答案:

您可以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

要转换intString,请使用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.816
2010年4月16日,星期五,格林尼治标准时间15:15:17
20100416151517


 类似资料: