如何获取Java中的当前日期/时间 [英] How to get the current date/time in Java

查看:80
本文介绍了如何获取Java中的当前日期/时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What's the best way to get the current date/time?

推荐答案

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

It depends on what form of date / time you want:


  • 如果您希望将日期/时间作为单个数值,则 System.currentTimeMillis ()给你,表示为UNIX时代之后的毫秒数(作为Java long )。该值是UTC时间点的增量,并且与本地时区无关...假设系统时钟设置正确。

  • If you want the date / time as a single numeric value, then System.currentTimeMillis() gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java long). This value is a delta from a UTC time-point, and is independent of the local time-zone ... assuming that the system clock has been set correctly.

如果您希望以允许您以数字方式访问组件(年,月等)的表单中的日期/时间,则可以使用以下方法之一:

If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:


  • new Date()给你一个 Date 约会时间。问题是, Date API方法主要有缺陷...已被弃用。

  • 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()给你一个使用当前日期/时间初始化的 Calendar 对象,使用默认的 Locale TimeZone 。其他重载可让您使用特定的 Locale 和/或 TimeZone 。日历工作...但API仍然很麻烦。

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.

新的org.joda.time.DateTime()为您提供了使用当前日期/时间初始化的 Joda-time 对象,使用默认时区和年表。有很多其他的Joda替代品...太多了,无法在这里描述。

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.

在Java 8中,调用 LocalDateTime.now() ZonedDateTime.now()将为您提供当前日期/时间的陈述。

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时间,则没有强烈的迁移理由。

Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations. With Java 8, this is no longer true. However, if you are already using Joda time in your codebase, there is no strong reason to migrate.

这篇关于如何获取Java中的当前日期/时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆