0

I'm trying to convert an int (which represents the military time hour) and convert it to its civilian time. For example if I have the hour "13" I want to convert it to "1:00 pm". Here's what I've been attempting:

private DateTimeFormatter hourFormat = DateTimeFormat.forPattern("hh:mm a");
private DateTimeFormatter dateFormat = DateTimeFormat.forPattern("YYYY-MM-dd");

int hour = 8;
DateTime fullDate = new DateTime();
 String date = dateFormat.print(fullDate) + " " + Integer.toString(hour) + ":00";
String civilianTime = hourFormat.parseDateTime(date).toString();

Logcat:

java.lang.IllegalArgumentException: Invalid format: "2016-01-27 8:00" is malformed at "16-01-27 8:00"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:945)

Joda doesn't allow me to just reformat the hour, I get a "8:00 too short" type of error so that is why I included the date and combined the date and time into one string even though I don't need date. I also have tried using a time zone component in there but I get the same error. Just for background: The int "hour" comes from timestamps (UTC w/ timezone offset) from a database query that spits out a list of hours I need. So the hours I get back have already taken timezone into account.

In essence I'm trying to go from "HH" hour of day (0-23) to "hh:mm a" clockhour of halfday (1-12). I'm assuming sometimes the "HH" is just "H" because the leading zero is dropped when going from database query to the application. I've tried this with hour = 8 and hour = 10 with the same resulting error.

M. Smith
  • 379
  • 1
  • 20
  • Why not use Calendar in the first place? You can do all of this easily with Calendar – dequec64 Jan 27 '16 at 16:34
  • 1
    If you have *just* the hour 13, you can simply use `new LocalTime(13, 0)`. – Andy Turner Jan 27 '16 at 16:36
  • @dequec64 This is just a few lines in a giant app that uses Joda because it is thread so I was trying to be consistent – M. Smith Jan 27 '16 at 16:40
  • BTW, the United States is about the only place that considers it “military time” versus “civilian time”. Most of the world uses 12-hour time for casual contexts, and [24-hour time](https://en.wikipedia.org/wiki/24-hour_clock) for serious contexts such as train schedules. Once you get used to 24-hour time you'll likely appreciate the clarity, the lack of AM-PM ambiguity. – Basil Bourque Jan 27 '16 at 19:48
  • @BasilBourque Thanks luckily this is for a US customer base. I need this for the UI – M. Smith Jan 27 '16 at 21:12

2 Answers2

3

Thanks to one of the comments to use LocalTime, this gets it done:

private DateTimeFormatter hourFormat = DateTimeFormat.forPattern("h:mm a");   
int hour = 8;
String ltime = new LocalTime(hour,0).toString(hourFormat);

In the format pattern, the DateTimeFormat class of Joda-time says to use:

  • h (lowercase) for clockhour of halfday (1~12)
  • H (uppercase) for hour of day (0~23)

Use a double hh if you want to pad a leading 0 (zero) for single digit values. For example to get 08:00 rather than 8:00. When parsing, any number of digits are accepted.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
M. Smith
  • 379
  • 1
  • 20
  • For hours above 12, you need the format placeholder `H` in a second SimpleDateFormat for parsing. The original with `hh` and `a` for the representation. – Joop Eggen Jan 27 '16 at 18:36
  • @JoopEggen I'm sorry I don't understand what you mean at all. haha I just tested for 13 (my local time) and it worked just how I wanted it. – M. Smith Jan 27 '16 at 19:04
  • The [`DateTimeFormat`](http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html) doc says: When parsing, any number of digits are accepted. – Basil Bourque Jan 27 '16 at 21:56
0

tl;dr

Use java.time rather than Joda-Time.

LocalTime.of( 13 , 0 )
         .format( 
             DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT )
                              .withLocale( Locale.US ) 
         )

1:00 PM

See this code run live at IdeOne.com.

…or…

ZonedDateTime.of(
    LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) ,  // Get today’s date at this moment in this time zone.
    LocalTime.of( 13 , 0 ) ,                            // Specify the time-of-day given to us. In this example `13` for 1 PM is given to us.
    ZoneId.of( "Pacific/Auckland" )                     // Specify the time zone giving the context for this date-time. 
).format(                                               // Generate a string representing the value of this date-time object.
     DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
                      .withLocale( Locale.US )          // Localize using the language and cultural norms of the United States.
 )

5/4/17 1:00 PM

Update

The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.

Using java.time

The LocalTime and LocalDate classes represent each part of a date-time without any offset-from-UTC nor time zone.

int hour = 13 ;  // 24-hour clock, 0-23. So `13` is 1 PM. 
LocalTime lt = LocalTime.of( hour , 0 ); // ( hours , minutes )

lt.toString(): 13:00

Let java.time localize for you.

To localize, specify:

  • FormatStyle to determine how long or abbreviated should the string be.
  • Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

    DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( Locale.US ) ; String output = lt.format( f );

output: 1:00 PM

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate ld = LocalDate.now( z );

ld.toString(): 2017-01-23

To arrive at a specific point on the timeline, we apply a time zone (ZoneId object) to get a ZonedDateTime.

ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;  // ( LocalDate , LocalTime , ZoneId )

zdt.toString(): 2017-01-23T13:00:00-05:00[America/Montreal]

Generate a string in your desired format. As seen above, let java.time localize for you.

DateTimeFormatter f2 = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT ).withLocale( Locale.US ) ;
String output2 = zdt.format( f2 );

5/4/17 1:00 PM

See this code run live at IdeOne.com.

Not really “military time”

By the way, the term “military time” in referring to the 24-hour clock is mainly a United States phenomenon as the US is one of the rare places where the 12-hour clock dominates.

Other people around the globe commonly use both, referring to 12-hour clock for casual matters and to 24-hour clock in critical matters such as train schedules. A much wiser practice in my experience.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154