Java 中的当前日期和时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11395378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Current Date & Time in Java
提问by Beginner
I want the current date and time in the following format :
我想要以下格式的当前日期和时间:
Date :YYYYMMDD
日期 :YYYYMMDD
Time : HHMMSS
时间 : HHMMSS
I tried the following
我尝试了以下
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println(new Date().getTime());
By this I am getting the desired date output but the time is coming in this way 1341837848290.
通过这种方式,我得到了所需的日期输出,但时间以这种方式 1341837848290。
The expected is HHMMSS.
预期是 HHMMSS。
回答by Jigar Joshi
Use format()
利用 format()
System.out.println(new SimpleDateFormat("HH:mm:SS").format(new Date()));
Date instance doesn't have any property to hold custom format, So you need to format the date instance to String with your custom format HH:mm:SS (See API docfor more detail)
日期实例没有任何属性来保存自定义格式,因此您需要使用自定义格式 HH:mm:SS 将日期实例格式化为字符串(有关更多详细信息,请参阅API 文档)
See
看
回答by Rajesh
try this
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
DateFormat timeFormat = new SimpleDateFormat("HHmmss");
Date d=new Date();
System.out.println(timeFormat.format(d);
回答by Scorpio
Did you check out the joda-time library? Link here
您是否查看了 joda-time 库?链接在这里
With joda-time, you could easily call new DateTime()
, call toString()
on it and have this output, which may be more what you want:
使用 joda-time,您可以轻松调用new DateTime()
、调用toString()
它并获得此输出,这可能更符合您的要求:
public static void main(final String[] args) {
final DateTime d = new DateTime();
System.out.println(d.toString());
}
Output: 2012-07-09T14:54:13.366+02:00
输出:2012-07-09T14:54:13.366+02:00
Joda-Time is very powerful on the plus side. Of course, this is an extra lib you need to include, and if this is not possible or desired, another approach would probably be better.
Joda-Time 在有利方面非常强大。当然,这是您需要包含的额外库,如果不可能或不希望这样做,另一种方法可能会更好。
回答by npinti
I tried this:
我试过这个:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmmss");
Date date = Calendar.getInstance().getTime();
System.out.println(sdf.format(date));
Yields:
产量:
20120709 145518
20120709 145518
First section is the date (20120709
), the second section is the time(145518
).
第一部分是日期(20120709
),第二部分是时间(145518
)。
It seems that you have been using the wrong notation. I would recommend you take a look herefor full details.
看来您一直在使用错误的符号。我建议您查看此处以获取完整详细信息。