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

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


当前回答

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

其他回答

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

如果你创建了一个新的Date对象,默认情况下它将被设置为当前时间:

import java.util.Date;
Date now = new Date();
import org.joda.time.DateTime;

DateTime now = DateTime.now();

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