如何在Java中获取当前日期和时间?
我正在寻找相当于DateTime的东西。现在从c#开始。
如何在Java中获取当前日期和时间?
我正在寻找相当于DateTime的东西。现在从c#开始。
当前回答
博士tl;
Instant.now()
java.time
date类已被新的java.util. date类淘汰。Java 8及更高版本中的time包(教程)。旧的java.util.Date/。日历类是出了名的麻烦、混乱和有缺陷。避免它们。
分区日期时间
在java.time中获取当前时刻。
ZonedDateTime now = ZonedDateTime.now();
一个zone datetime封装:
日期。 一天中的时间,具有几分之一秒到纳秒的分辨率。 时区。
如果没有指定时区,JVM的当前默认时区将以静默方式分配。最好指定您想要的/预期的时区,而不是隐式地依赖默认时区。
ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.now( z );
UTC
通常最好养成在UTC时区内完成后端工作(业务逻辑、数据库、存储、数据交换)的习惯。上面的代码隐式地依赖于JVM当前的默认时区。
Instant类表示UTC时间轴上的一个时刻,分辨率为纳秒。
Instant instant = Instant.now();
Instant类是java中一个基本的构建块类。时间和可能经常在代码中使用。
当您需要更灵活的格式时,可以转换为OffsetDateTime。指定一个ZoneOffset对象。对于UTC,使用方便的常量For UTC。
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
时区
您可以轻松地调整到另一个时区,以便向用户显示。使用正确的时区名称,不要使用3-4个字母的代码,如EST或IST。
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime nowMontreal = instant.atZone( z );
生成该日期-时间值的字符串表示,并进行本地化。
String output = DateTimeFormatter
.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH )
.format ( nowMontreal );
即时
或者,要保持UTC,请使用即时。Instant对象表示时间轴上的时刻,以纳秒分辨率表示,始终以UTC为单位。这为分区日期-时间以及时区分配提供了构建块。你可以这样理解:
分区日期时间 = 即时 + 区域 ID
您可以从zone datetime中提取一个Instant。
Instant instantNow = zdt.toInstant();
你可以从速溶开始。这里不需要指定时区,因为Instant总是使用UTC。
Instant now = Instant.now();
其他回答
我更喜欢使用Calendar对象。
Calendar now = GregorianCalendar.getInstance()
我觉得用起来容易多了。您还可以从Calendar中获取Date对象。
http://java.sun.com/javase/6/docs/api/java/util/GregorianCalendar.html
在Java 8中,它是:
ZonedDateTime dateTime = ZonedDateTime.now();
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.
LocalDateTime timePoint = LocalDateTime.now();
System.out.println(timePoint);
根据文件:
now()方法使用系统返回当前日期-时间 时钟和默认时区,不是空。它得到电流 来自默认时区中的系统时钟的日期-时间。这将 在默认时区查询系统时钟,获取当前时间 日期-时间。使用这种方法将阻止使用的能力 测试的备用时钟,因为时钟是硬编码的。
如果你创建了一个新的Date对象,默认情况下它将被设置为当前时间:
import java.util.Date;
Date now = new Date();
java.lang.System.currentTimeMillis ();将返回自epoch以来的datetime