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

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


当前回答

在Java 8中,它是:

ZonedDateTime dateTime = ZonedDateTime.now();

其他回答

我更喜欢使用Calendar对象。

Calendar now = GregorianCalendar.getInstance()

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

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

import java.util.Date;   
Date now = new Date();

注意,Date对象是可变的,如果您想做一些复杂的事情,请使用jodatime。

在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 d = new Date();

用Javadocs零参数构造函数的话说:

分配Date对象并初始化它,使它表示分配的时间,测量到最近的毫秒。

确保您使用的是java.util.Date而不是java.sql.Date——后者没有零参数构造函数,并且具有一些不同的语义,这是完全不同的对话主题。:)