如何在Java中获取当前日期和时间?

我正在寻找相当于DateTime的东西。现在从c#开始。


当前回答

我更喜欢使用Calendar对象。

Calendar now = GregorianCalendar.getInstance()

我觉得用起来容易多了。您还可以从Calendar中获取Date对象。

http://java.sun.com/javase/6/docs/api/java/util/GregorianCalendar.html

其他回答

java.lang.System.currentTimeMillis ();将返回自epoch以来的datetime

在Java 8中,它是:

ZonedDateTime dateTime = ZonedDateTime.now();

许多人认为Java Date和Calendar类设计得很糟糕。您应该看一看Joda Time,这是一个常用来代替Java内置日期库的库。

相当于DateTime。现在在Joda时间是:

DateTime dt = new DateTime();

更新

正如评论中所指出的,最新版本的Joda Time有一个DateTime.now()方法,因此:

DateTime dt = DateTime.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()方法使用系统返回当前日期-时间 时钟和默认时区,不是空。它得到电流 来自默认时区中的系统时钟的日期-时间。这将 在默认时区查询系统时钟,获取当前时间 日期-时间。使用这种方法将阻止使用的能力 测试的备用时钟,因为时钟是硬编码的。

我更喜欢使用Calendar对象。

Calendar now = GregorianCalendar.getInstance()

我觉得用起来容易多了。您还可以从Calendar中获取Date对象。

http://java.sun.com/javase/6/docs/api/java/util/GregorianCalendar.html