Joda DateTimeFormatter know if AM or PM

1k Views Asked by At

I'm using Joda's DateTimeFormatter to get formatted date and time.

DateTimeFormatter hour = DateTimeFormat.forPattern("aa").withLocale(locale);

System.out.println(hour.print(mydateObj));

Since I'm using DateTimeFormatter with locale, how can I know whether the time is AM or PM ?

1

There are 1 best solutions below

4
On

It is not clear what the type of "myDateObj" is so I have to guess somehow. But one thing is for sure. You cannot use the formatter for querying if a time is AM or PM because this information does not form a part of the state of the formatter. A formatter is not an "hour" so your variable name is totally misleading. You might theoretically ask if the printed output is equal to "AM" or "PM" (in English). But there is a much better approach which does not depend on any locale setting.

Joda-Time offers various types like LocalTime, LocalDateTime or DateTime which know the method getHourOfDay(). Note there is no direct access to AM/PM itself. But it is easy to do following small calculation:

public static boolean isAM(DateTime time) {
    return time.getHourOfDay() < 12;
}