javadatedatetimedatetime-formatjodatime

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"

Solution

  • 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.