本文翻译自:Equivalent of C#'s DateTime.Now in Java?
How do I get the current date in Java? 如何在Java中获取当前日期?
In C# it is DateTime.Now
. 在C#中,它是DateTime.Now
。
#1楼
参考:https://stackoom.com/question/8Qxw/相当于C-的DateTime-Now在Java中
#2楼
import org.joda.time.DateTime;
DateTime now = DateTime.now();
#3楼
Just construct a new Date
object without any arguments; 只需构造一个没有任何参数的新Date
对象; this will assign the current date and time to the new object. 这会将当前日期和时间分配给新对象。
import java.util.Date;
Date d = new Date();
In the words of the Javadocs for the zero-argument constructor : 用零参数构造函数 的Javadocs的话来说:
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
- 后者没有零参数构造函数,并且有一些不同的语义,这是完全不同的对话的主题。 :) :)
#4楼
import java.util.Date;
Date now = new Date();
Note that the Date object is mutable and if you want to do anything sophisticated, use jodatime . 请注意, Date对象是可变的,如果你想做任何复杂的事情,请使用jodatime 。
#5楼
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();
#6楼
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. 您还可以从日历中获取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