Java 如何获取当前日期和时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2010284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the current date and time
提问by mrblah
How do I get the current date and time in Java?
如何在 Java 中获取当前日期和时间?
I am looking for something that is equivalent to DateTime.Now
from C#.
我正在寻找DateTime.Now
与 C#等效的东西。
采纳答案by delfuego
Just construct a new Date
object without any arguments; this will assign the current date and time to the new object.
只构造一个Date
没有任何参数的新对象;这会将当前日期和时间分配给新对象。
import java.util.Date;
Date d = new Date();
In the words of the Javadocsfor 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.
分配一个 Date 对象并初始化它,以便它表示它被分配的时间,测量到最接近的毫秒。
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. :)
确保您正在使用java.util.Date
而不是java.sql.Date
- 后者没有零参数构造函数,并且具有一些不同的语义,这些语义是完全不同的对话的主题。:)
回答by Chandra Patni
回答by parkerfath
If you create a new Date object, by default it will be set to the current time:
如果你创建一个新的 Date 对象,默认情况下它会被设置为当前时间:
import java.util.Date;
Date now = new Date();
回答by ralph
I prefer using the Calendar object.
我更喜欢使用 Calendar 对象。
Calendar now = GregorianCalendar.getInstance()
I find it much easier to work with. You can also get a Date object from the Calendar.
我发现与它合作要容易得多。您还可以从 Calendar 中获取 Date 对象。
http://java.sun.com/javase/6/docs/api/java/util/GregorianCalendar.html
http://java.sun.com/javase/6/docs/api/java/util/GregorianCalendar.html
回答by cdmckay
The Java Dateand Calendarclasses 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.
许多人认为Java Date和Calendar类的设计很差。您应该查看Joda Time,这是一个常用来代替 Java 内置日期库的库。
The equivalent of DateTime.Now
in Joda Time is:
DateTime.Now
Joda Time 中的等价物是:
DateTime dt = new DateTime();
Update
更新
As noted in the comments, the latest versions of Joda Time have a DateTime.now()
method, so:
如评论中所述,最新版本的 Joda Time 有一个DateTime.now()
方法,因此:
DateTime dt = DateTime.now();
回答by user243773
java.lang.System.currentTimeMillis();
will return the datetime since the epoch
java.lang.System.currentTimeMillis();
将返回自纪元以来的日期时间
回答by gordy
import org.joda.time.DateTime;
DateTime now = DateTime.now();
回答by Vitalii Fedorenko
In Java 8 it's:
在 Java 8 中,它是:
ZonedDateTime dateTime = ZonedDateTime.now();
回答by Basil Bourque
tl;dr
tl;博士
Instant.now()
java.time
时间
The java.util.Date class has been outmoded by the new java.time package(Tutorial) in Java 8 and later. The old java.util.Date/.Calendar classes are notoriously troublesome, confusing, and flawed. Avoid them.
java.util.Date 类已被Java 8 及更高版本中的新java.time 包( Tutorial)过时。旧的 java.util.Date/.Calendar 类是出了名的麻烦、混乱和有缺陷。避开它们。
ZonedDateTime
ZonedDateTime
Get the current moment in java.time.
在 java.time 中获取当前时刻。
ZonedDateTime now = ZonedDateTime.now();
A ZonedDateTime
encapsulates:
AZonedDateTime
封装:
- Date.
- Time-of-day, with a fraction of a second to nanosecondresolution.
- Time zone.
- 日期。
- 一天中的时间,以几分之一秒到纳秒的分辨率。
- 时区。
If no time zone is specified, your JVM's current default time zone is assigned silently. Better to specify your desired/expected time zone than rely implicitly on default.
如果未指定时区,则以静默方式分配 JVM 的当前默认时区。最好指定您想要/预期的时区,而不是隐式依赖默认值。
ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.now( z );
UTC
世界标准时间
Generally better to get in the habit of doing your back-end work (business logic, database, storage, data exchange) all in UTCtime zone. The code above relies implicitly on the JVM's current default time zone.
通常最好养成在UTC时区进行后端工作(业务逻辑、数据库、存储、数据交换)的习惯。上面的代码隐式依赖于 JVM 的当前默认时区。
The Instant
class represents a moment in the timeline in UTC with a resolution of nanoseconds.
本Instant
类代表在UTC时间线与纳秒的分辨率的时刻。
Instant instant = Instant.now();
The Instant
class is a basic building-block class in java.time and may be used often in your code.
该Instant
班是java.time一个基本构建块级和可在代码中经常使用。
When you need more flexibility in formatting, transform into an OffsetDateTime
. Specify a ZoneOffset
object. For UTC use the handy constant for UTC.
当您需要更灵活的格式设置时,请转换为OffsetDateTime
. 指定一个ZoneOffset
对象。对于 UTC 使用方便的常量 UTC。
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
Time Zone
时区
You easily adjust to another time zone for presentation to the user. Use a proper time zone name, neverthe 3-4 letter codes such as EST
or IST
.
您可以轻松调整到另一个时区以向用户展示。使用正确的时区名称,不要使用 3-4 个字母的代码,例如EST
或IST
。
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime nowMontreal = instant.atZone( z );
Generate a String representation of that date-time value, localized.
生成本地化的该日期时间值的字符串表示形式。
String output = DateTimeFormatter
.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH )
.format ( nowMontreal );
Instant
Instant
Or, to stay in UTC, use Instant
. An Instant
object represents a moment on the timeline, to nanosecond resolution, always in UTC. This provides the building block for a zoned date-time, along with a time zone assignment. You can think of it conceptually this way:
或者,要保持 UTC,请使用Instant
. 一个Instant
对象代表时间轴上的一个时刻,精度为纳秒,始终采用 UTC。这提供了分区日期时间的构建块,以及时区分配。你可以从概念上这样想:
You can extract an Instant
from a ZonedDateTime
.
您可以Instant
从ZonedDateTime
.
Instant instantNow = zdt.toInstant();
You can start with an Instant. No need to specify a time zone here, as Instant
is always in UTC.
您可以从 Instant 开始。无需在此处指定时区,就像Instant
在 UTC 中一样。
Instant now = Instant.now();
回答by akhil_mittal
Java has always got inadequate support for the date and time use cases. For example, the existing classes (such as java.util.Date
and SimpleDateFormatter
) aren't thread-safe which can lead to concurrency issues. Also there are certain flaws in API. For example, years in java.util.Date
start at 1900, months start at 1, and days start at 0—not very intuitive. These issues led to popularity of third-party date and time libraries, such as Joda-Time
. To address a new date and time API is designed for Java SE 8.
Java 对日期和时间用例的支持一直不够。例如,现有的类(如java.util.Date
和SimpleDateFormatter
)不是线程安全的,这可能会导致并发问题。API 中也存在某些缺陷。例如,年份java.util.Date
从 1900 开始,月份从 1 开始,天从 0 开始——不是很直观。这些问题导致了第三方日期和时间库的流行,例如Joda-Time
. 为了解决新的日期和时间 API 是为 Java SE 8 设计的。
LocalDateTime timePoint = LocalDateTime.now();
System.out.println(timePoint);
As per doc:
根据文档:
The method
now()
returns the current date-time using the system clock and default time-zone, not null. It obtains the current date-time from the system clock in the default time-zone. This will query the system clock in the default time-zone to obtain the current date-time. Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.
该方法
now()
使用系统时钟和默认时区返回当前日期时间,而不是 null。它从默认时区的系统时钟中获取当前日期时间。这将查询默认时区中的系统时钟以获取当前日期时间。使用此方法将阻止使用备用时钟进行测试的能力,因为该时钟是硬编码的。