Java 以 yyyy-MM-dd hh.mm.ss 格式获取当前日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20625794/
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
get current date time in yyyy-MM-dd hh.mm.ss format
提问by CodeMed
I have an application which will ALWAYS be run in only one single time zone, so I do not need to worry about converting between time zones. However, the datetime must always be printed out in the following format:
我有一个应用程序,它总是只在一个时区运行,所以我不需要担心时区之间的转换。但是,必须始终按以下格式打印日期时间:
yyyy-MM-dd hh.mm.ss
The code below fails to print the proper format:
下面的代码无法打印正确的格式:
public void setCreated(){
DateTime now = new org.joda.time.DateTime();
String pattern = "yyyy-MM-dd hh.mm.ss";
created = DateTime.parse(now.toString(), DateTimeFormat.forPattern(pattern));
System.out.println("''''''''''''''''''''''''''' created is: "+created);
}
The setCreated() method results in the following output:
setCreated() 方法产生以下输出:
"2013-12-16T20:06:18.672-08:00"
How can I change the code in setCreated() so that it prints out the following instead:
如何更改 setCreated() 中的代码,以便它打印出以下内容:
"2013-12-16 20:06:18"
采纳答案by Sotirios Delimanolis
You aren't parsing anything, you are formatting it. You need to use DateTimeFormatter#print(ReadableInstant)
.
你没有解析任何东西,你正在格式化它。您需要使用DateTimeFormatter#print(ReadableInstant)
.
DateTime now = new org.joda.time.DateTime();
String pattern = "yyyy-MM-dd hh.mm.ss";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
String formatted = formatter.print(now);
System.out.println(formatted);
which prints
哪个打印
2013-12-16 11.13.24
This doesn't match your format, but I'm basing it on your code, not on your expected output.
这与您的格式不匹配,但我基于您的代码,而不是您的预期输出。
回答by Lijo
public static void main(String args[])
{
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
System.out.println(strDate);
}
out put 2013-12-17 09:48:11
输出 2013-12-17 09:48:11
回答by AmirtharajCVijay
回答by rocks
Try this:
尝试这个:
org.joda.time.DateTime now = new org.joda.time.DateTime();
String pattern = "yyyy-MM-dd hh.mm.ss";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
String formatted = formatter.print(now);
LocalDateTime date = formatter.parseLocalDateTime(formatted);
System.out.println(date.toDateTime());
回答by totran
And now in Java 9, you can use this:
现在在 Java 9 中,你可以使用这个:
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh.mm.ss"));