How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

后端 未结 10 1967
渐次进展
渐次进展 2020-11-29 16:58

How can I get the year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java? I would like to have them as Strings.

10条回答
  •  孤独总比滥情好
    2020-11-29 17:12

    You can use the getters of java.time.LocalDateTime for that.

    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);
    

    Or, when you're not on Java 8 yet, make use of 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);
    

    Either way, this prints as of now:

    2010-04-16 15:15:17.816
    

    To convert an int to String, make use of String#valueOf().


    If your intent is after all to arrange and display them in a human friendly string format, then better use either Java8's java.time.format.DateTimeFormatter (tutorial here),

    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);
    

    or when you're not on Java 8 yet, use 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);
    

    Either way, this yields:

    2010-04-16T15:15:17.816
    Fri, 16 Apr 2010 15:15:17 GMT
    20100416151517
    

    See also:

    • Java string to date conversion

提交回复
热议问题