Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 24-hour clock time to am/pm in Joda-Time

Tags:

java

jodatime

I just started working with Joda-Time, and got it to correctly display my date in 24-hour clock ("military time") but I would rather it be am/pm. Looked it up and it mentioned hourOfDay which I figured was the HH value so I tried to write a loop that would break it down into AM/Pm but it never worked out.

    DateTime dtf = new DateTime(wikiParsedDate);


    if (hourOfDay == 00) {
        hourOfDay == 12;
        DateTimeFormatter builder = DateTimeFormat.forPattern( "dd-MM-yyyy HH:mm:ss.SS'AM" );
        return builder.print(dtf);
    } else if (0 < hourOfDay && hourOfDay < 12) {
        DateTimeFormatter builder = DateTimeFormat.forPattern( "dd-MM-yyyy HH:mm:ss.SS'AM" );
        return builder.print(dtf);
    } else if (hourOfDay > 12) {
        hourOfDay - 12 == hourOfDay;
        DateTimeFormatter builder = DateTimeFormat.forPattern( "dd-MM-yyyy HH:mm:ss.SS'PM" );
        return builder.print(dtf);
    }

}
like image 694
Sam Haito Avatar asked Sep 29 '13 06:09

Sam Haito


People also ask

What is Joda-Time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat.

How do I change the date format in Joda-time?

How to change the SimpleDateFormat to jodatime? String s = "2014-01-15T14:23:50.026"; DateTimeFormatter dtf = DateTimeFormat. forPattern("yyyy-MM-dd'T'HH:mm:ss. SSSS"); DateTime instant = dtf.

Does Joda DateTime have time zones?

Adjusting Time ZoneUse the DateTimeZone class in Joda-Time to adjust to a desired time zone. Joda-Time uses immutable objects. So rather than change the time zone ("mutate"), we instantiate a new DateTime object based on the old but with the desired difference (some other time zone). Use proper time zone names.

Is Joda-Time deprecated?

So the short answer to your question is: YES (deprecated).


1 Answers

Look at the API documentation of DateTimeFormat. This should do what you want:

DateTimeFormatter builder = DateTimeFormat.forPattern("dd-MM-yyyy hh:mm:ss.SSa");

No need for the complication with different cases.

like image 127
Jesper Avatar answered Oct 19 '22 15:10

Jesper