2

I am working on android project and i receive from API the time in format like this "10:12:57 am" (12 hour format) and I want to display it in format "10:12" just like this (on a 24 hour clock). How to reformat that time?

So 12:42:41 am should become 00:42. And 02:13:39 pm should be presented as 14:13.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Muhammad Adam
  • 147
  • 1
  • 10
  • Is the returned object from the API a String? If "10:12:57 am" is a String then you simply use `substring(0,5)` to get the first five characters from the String. – Huzaifa Iftikhar Sep 23 '18 at 12:49
  • 1
    Possible [Duplicate](https://stackoverflow.com/questions/15132878/hours-and-minutes-from-date-in-android) – Akshay Nandwana Sep 23 '18 at 12:51
  • 1
    @HuzaifaIftikhar but it is 12 hours system, and i want it in 24 hours – Muhammad Adam Sep 23 '18 at 13:08
  • How will the API return the time when the hours is less than 10? Is it like "09:12:57 am" or "9:12:57 am"? Depending on this you can easily convert it to 24-hour format on your own. – Huzaifa Iftikhar Sep 23 '18 at 13:12
  • 1
    Not a duplicate of [that linked Question](https://stackoverflow.com/q/15132878/642706). That Question involves a moment, a date with time-of-day and with an offset-from-UTC. This Question is about a time-of-day alone, no date, no offset, no time zone. – Basil Bourque Sep 24 '18 at 00:46
  • Ideally the API should be able to give you a string in ISO 8601 format, that is, like `10:12:57` (24 hours). And yiou should display the time according to the user’s locale. – Ole V.V. Sep 24 '18 at 02:31

5 Answers5

3

Using java.time (Modern Approach)

String str = "10:12:57 pm";

DateTimeFormatter formatter_from = DateTimeFormatter.ofPattern( "hh:mm:ss a", Locale.US ); //Use pattern symbol "hh" for 12 hour clock
LocalTime localTime = LocalTime.parse(str.toUpperCase(), formatter_from );
DateTimeFormatter formatter_to = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US ); // "HH" stands for 24 hour clock

System.out.println(localTime.format(formatter_to));

See BasilBourque answer below and OleV.V. answer here for better explanation.

Using SimpleDateFormat

String str = "10:12:57 pm";

    SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss a", Locale.US); 

    //Locale is optional. You might want to add it to avoid any cultural differences.

    SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm", Locale.US);

    try {
        Date d = formatter_from.parse(str);

        System.out.println(formatter_to.format(d));

    } catch (ParseException e) {           
        e.printStackTrace();
    }

If your input is 10:12:57 am, output will be 10:12. And if string is 10:12:57 pm, output will be 22:12.

itsmysterybox
  • 2,748
  • 3
  • 21
  • 26
  • error ==> Unparseable date : "10:12:57 am" at offset 9 – Muhammad Adam Sep 23 '18 at 13:35
  • Visit [this](https://stackoverflow.com/questions/24030767/java-text-parseexception-unparseable-date-2014-06-04-at-offset-5) – itsmysterybox Sep 23 '18 at 13:39
  • Not at all but edit your answer to be like mine to every provide from it .thanks – Muhammad Adam Sep 23 '18 at 14:15
  • 2
    FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Sep 24 '18 at 00:34
  • 1
    This code misuses a date-with-time-of-day class to hold a time-of-day-only value. Square peg in a round hole. – Basil Bourque Sep 24 '18 at 00:42
1

tl;dr

LocalTime                                                    // Represent a time-of-day, without a date and without a time zone.
.parse(                                                      // Parse an input string to be a `LocalTime` object.
    "10:12:57 am".toUpperCase() ,                            // The cultural norm in the United States expects the am/pm to be in all-uppercase. So we convert our input value to uppercase.
    DateTimeFormatter.ofPattern( "hh:mm:ss a" , Locale.US )  // Specify a formatting pattern to match the input. 
)                                                            // Returns a `LocalTime` object.
.format(                                                     // Generate text representing the value in this date-time object.
    DateTimeFormatter.ofPattern( "HH:mm" , Locale.US )       // Note that `HH` in uppercase means 24-hour clock, not 12-hour.
)                                                            // Returns a `String`.

10:12

java.time

The modern approach uses the java.time classes that years ago supplanted the terrible Date & Calendar & SimpleDateFormat classes.

The LocalTime class represents a time-of-day in a generic 24-hour day, without a date and without a time zone.

Parse your string input as a LocalTime object.

String input = ( "10:12:57 am" );
DateTimeFormatter fInput = DateTimeFormatter.ofPattern( "HH:mm:ss a" , Locale.US );
LocalTime lt = LocalTime.parse( input.toUpperCase() , fInput );  // At least in the US locale, the am/pm is expected to be in all uppercase: AM/PM. So we call `toUppercase` to convert input accordingly.

lt.toString(): 10:12:57

Generate a String with text in the hour-minute format you desire. Note that HH in uppercase means 24-hour clock.

DateTimeFormatter fOutput = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US );
String output = lt.format( fOutput );

output: 10:12


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.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

You can use such formatters:

SimpleDateFormat formatterFrom = new SimpleDateFormat("hh:mm:ss aa");
SimpleDateFormat formatterTo = new SimpleDateFormat("HH:mm");

Date date = formatterFrom.parse("10:12:57 pm");
System.out.println(formatterTo.format(date));
Feedforward
  • 4,521
  • 4
  • 22
  • 34
0

Try this:

   SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
   SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
   try {
         Date date = parseFormat.parse("10:12:57 pm");
         System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
       } 
   catch (Exception e) {
         e.printStackTrace();
       }  

The gives:

10:12:57 pm = 22:12
Huzaifa Iftikhar
  • 755
  • 1
  • 6
  • 9
0
String str ="10:12:57 pm";

SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss aa", Locale.US);
SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm",Locale.US);

try {
    Date d = formatter_from.parse(str);

    System.out.println(formatter_to.format(d));

} catch (ParseException e) {           
    e.printStackTrace();
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Muhammad Adam
  • 147
  • 1
  • 10
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously troublesome SimpleDateFormat class. At least not as the first option. And not without any reservation. Today we have so much better in [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Sep 24 '18 at 02:36