How to get the current date and time

后端 未结 10 445
无人共我
无人共我 2020-11-29 16:59

How do I get the current date and time in Java?

I am looking for something that is equivalent to DateTime.Now from C#.

相关标签:
10条回答
  • 2020-11-29 17:34

    Just construct a new Date object without any arguments; this will assign the current date and time to the new object.

    import java.util.Date;
    
    Date d = new Date();
    

    In the words of the Javadocs for the zero-argument constructor:

    Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

    Make sure you're using java.util.Date and not java.sql.Date -- the latter doesn't have a zero-arg constructor, and has somewhat different semantics that are the topic of an entirely different conversation. :)

    0 讨论(0)
  • 2020-11-29 17:34

    java.lang.System.currentTimeMillis(); will return the datetime since the epoch

    0 讨论(0)
  • 2020-11-29 17:37

    In Java 8 it's:

    ZonedDateTime dateTime = ZonedDateTime.now();
    
    0 讨论(0)
  • 2020-11-29 17:38

    The Java Date and Calendar classes are considered by many to be poorly designed. You should take a look at Joda Time, a library commonly used in lieu of Java's built-in date libraries.

    The equivalent of DateTime.Now in Joda Time is:

    DateTime dt = new DateTime();
    

    Update

    As noted in the comments, the latest versions of Joda Time have a DateTime.now() method, so:

    DateTime dt = DateTime.now();
    
    0 讨论(0)
  • 2020-11-29 17:38
    import java.util.Date;   
    Date now = new Date();
    

    Note that the Date object is mutable and if you want to do anything sophisticated, use jodatime.

    0 讨论(0)
  • 2020-11-29 17:51
    import org.joda.time.DateTime;
    
    DateTime now = DateTime.now();
    
    0 讨论(0)
提交回复
热议问题