如何在java中获取当前日期/时间

问题:

获取当前日期/时间的最佳方法是什么?

回答:

这取决于你想要的日期/时间的形式:

  • 如果要将日期/时间作为单个数值,则System.currentTimeMillis()给出,表示为UNIX时代之后的毫秒数(作为Java long)。该值是UTC时间点的增量,并且与本地时区无关…假设系统时钟已正确设置。
  • 如果您希望以允许您以数字方式访问组件(年,月等)的表单中的日期/时间,则可以使用以下之一:
     

    • new Date() gives you a Date object initialized with the current date / time. The problem is that the Date API methods are mostly flawed … and deprecated.

    • Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. Other overloads allow you to use a specific Locale and/or TimeZone. Calendar works … but the APIs are still cumbersome.

    • new org.joda.time.DateTime() gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives … too many to describe here.

    • in Java 8, calling LocalDateTime.now() and ZonedDateTime.now() will give you representations for the current date / time.

在Java 8之前,大多数知道这些事情的人推荐Joda-time拥有最好的Java API来处理涉及时间和持续时间计算的事情。使用Java 8,这不再是真的。但是,如果您已经在代码库中使用了Joda时间,则没有强大的1迁移原因。
 1 – Your code won’t break if you don’t, and you won’t get deprecation warnings. Sure, the Joda codebase will probably stop getting updates, but it is unlikely to need them. No updates means stability and that is a good thing.

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: How to get the current date/time in java

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

− 5 = 5