如何获取当前日期和时间 [英] How to get the current date and time
问题描述
如何获取Java中的当前日期和时间?
How do I get the current date and time in Java?
我正在寻找与C#中的DateTime.Now
等效的东西.
I am looking for something that is equivalent to DateTime.Now
from C#.
推荐答案
只需构造一个没有任何参数的新Date
对象;这会将当前日期和时间分配给新对象.
Just construct a new Date
object without any arguments; this will assign the current date and time to the new object.
import java.util.Date;
Date d = new Date();
用 Javadocs的话来说用于零参数构造函数:
分配一个Date对象并初始化它,以便它表示分配它的时间,以最近的毫秒为单位.
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
请确保您使用的是java.util.Date
而不是java.sql.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. :)
这篇关于如何获取当前日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!