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

后端 未结 10 1977
渐次进展
渐次进展 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:24

    Switch to joda-time and you can do this in three lines

    DateTime jodaTime = new DateTime();
    
    DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS");
    System.out.println("jodaTime = " + formatter.print(jodaTime));
    

    You also have direct access to the individual fields of the date without using a Calendar.

    System.out.println("year = " + jodaTime.getYear());
    System.out.println("month = " + jodaTime.getMonthOfYear());
    System.out.println("day = " + jodaTime.getDayOfMonth());
    System.out.println("hour = " + jodaTime.getHourOfDay());
    System.out.println("minute = " + jodaTime.getMinuteOfHour());
    System.out.println("second = " + jodaTime.getSecondOfMinute());
    System.out.println("millis = " + jodaTime.getMillisOfSecond());
    

    Output is as follows:

    jodaTime = 2010-04-16 18:09:26.060
    
    year = 2010
    month = 4
    day = 16
    hour = 18
    minute = 9
    second = 26
    millis = 60
    

    According to http://www.joda.org/joda-time/

    Joda-Time is the de facto standard date and time library for Java. From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310).

提交回复
热议问题