简体   繁体   English

以yyyy-MM-dd hh.mm.ss格式获取当前日期时间

[英]get current date time in yyyy-MM-dd hh.mm.ss format

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"

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. 这与您的格式不符,但我的基础是您的代码,而不是您的预期输出。

 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

try this 尝试这个

        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
        Date now = new Date();
        String strDate = sdfDate.format(now);
        System.out.println(strDate);

demo 演示

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());

现在在Java 9中,您可以使用:

LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh.mm.ss"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM