简体   繁体   中英

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:

"2013-12-16T20:06:18.672-08:00"

How can I change the code in setCreated() so that it prints out the following instead:

"2013-12-16 20:06:18"

You aren't parsing anything, you are formatting it. You need to use 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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