您可以
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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)