39

In my app, I have a requirement to format 12 hours time to 24 hours time. What is the method I have to use?

For example, time like 10:30 AM. How can I convert to 24 hours time in java?

Sandeep Kumar
  • 2,397
  • 5
  • 30
  • 37
koti
  • 3,681
  • 5
  • 34
  • 58

17 Answers17

100

Try this:

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
   public static void main(String [] args) throws Exception {
       SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
       SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
       Date date = parseFormat.parse("10:30 PM");
       System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
   }
}

which produces:

10:30 PM = 22:30

See: http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • 3
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), `java.util.Calendar`, and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). See modern solution using *java.time* in [Answer by Cloud](https://stackoverflow.com/a/37388524/642706). – Basil Bourque Oct 17 '18 at 19:02
35

java.time

In Java 8 and later it could be done in one line using class java.time.LocalTime.

In the formatting pattern, lowercase hh means 12-hour clock while uppercase HH means 24-hour clock.

Code example:

String result =                                       // Text representing the value of our date-time object.
    LocalTime.parse(                                  // Class representing a time-of-day value without a date and without a time zone.
        "03:30 PM" ,                                  // Your `String` input text.
        DateTimeFormatter.ofPattern(                  // Define a formatting pattern to match your input text.
            "hh:mm a" ,
            Locale.US                                 // `Locale` determines the human language and cultural norms used in localization. Needed here to translate the `AM` & `PM` value.
        )                                             // Returns a `DateTimeFormatter` object.
    )                                                 // Return a `LocalTime` object.
    .format( DateTimeFormatter.ofPattern("HH:mm") )   // Generate text in a specific format. Returns a `String` object.
;

See this code run live at IdeOne.com.

15:30

See Oracle Tutorial.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Cloud
  • 983
  • 11
  • 11
  • 1
    I am not sure, but I suspect the "AM"/"PM" portions of the string may be localized. You may need to pass a `Locale` such as `Locale.US` as the optional second argument to `ofPattern` if at runtime the JVM’s current `Locale` is a mismatch to the input text. – Basil Bourque Oct 17 '18 at 18:59
  • For Android: https://developer.android.com/studio/write/java8-support – Dr.jacky Nov 25 '20 at 15:28
13

Assuming that you use SimpleDateFormat implicitly or explicitly, you need to use H instead of h in the format string.

E.g

HH:mm:ss

instead of

hh:mm:ss

realPK
  • 2,630
  • 29
  • 22
fvu
  • 32,488
  • 6
  • 61
  • 79
5

12 to 24 hour time conversion and can be reversed if change time formate in output and input SimpleDateFormat class parameter

Test Data Input:

String input = "07:05:45PM"; timeCoversion12to24(input);

output

19:05:45

 public static String timeCoversion12to24(String twelveHoursTime) throws ParseException {

        //Date/time pattern of input date (12 Hours format - hh used for 12 hours)
        DateFormat df = new SimpleDateFormat("hh:mm:ssaa");

        //Date/time pattern of desired output date (24 Hours format HH - Used for 24 hours)
        DateFormat outputformat = new SimpleDateFormat("HH:mm:ss");
        Date date = null;
        String output = null;

        //Returns Date object
        date = df.parse(twelveHoursTime);

        //old date format to new date format
        output = outputformat.format(date);
        System.out.println(output);

        return output;
    }
Arpan Saini
  • 4,623
  • 1
  • 42
  • 50
2
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a"); 

provided by Bart Kiers answer should be replaced with somethig like

SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a",Locale.UK);
user3172824
  • 301
  • 1
  • 2
  • 8
2

Try This

public static String convertTo24Hour(String Time) {
    DateFormat f1 = new SimpleDateFormat("hh:mm a"); //11:00 pm
    Date d = null;
    try {
        d = f1.parse(Time);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    DateFormat f2 = new SimpleDateFormat("HH:mm");
    String x = f2.format(d); // "23:00"

    return x;
}
TheRealChx101
  • 1,468
  • 21
  • 38
1
   static String timeConversion(String s)
   {
    String s1[]=s.split(":");
    char c[]=s1[2].toCharArray();
    if(s1[2].contains("PM"))
    {
        int n=Integer.parseInt(s1[0]);
        n=n+12;
        return n+":"+s1[1]+":"+c[0]+c[1];
    }
    else``
    return s1[0]+":"+s1[1]+":"+c[0]+c[1];
     }
Dheeraj
  • 11
  • 1
1

It can be done using Java8 LocalTime. Here is the code.

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class TimeConversion {
    public String timeConversion(String s) {  
        LocalTime.parse(s, DateTimeFormatter.ofPattern("hh:mm a"));    
    }
}

And Here is the test case for the same:

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class TimeConversionTest {

    @Test
    void shouldReturnTimeIn24HrFormat() {
        TimeConversion timeConversion = new TimeConversion();            
        Assertions.assertEquals("22:30", timeConversion.timeConversion("10:30 PM"));

    }

}
0

Using LocalTime in Java 8, LocalTime has many useful methods like getHour() or the getMinute() method,

For example,

LocalTime intime = LocalTime.parse(inputString, DateTimeFormatter.ofPattern("h:m a"));
String outtime = intime.format(DateTimeFormatter.ISO_LOCAL_TIME);

In some cases, First line alone can do the required parsing

venkata
  • 447
  • 3
  • 15
  • 1
    Duplicate Answer; see [original Answer by Cloud](https://stackoverflow.com/a/37388524/642706). And the code seen here fails, having omitted a SPACE found in the Question’s data. – Basil Bourque Nov 06 '17 at 04:13
  • LocalTime by default gives the 24 hour format, so first line itself will give the required format, no need to format it again and I do not have permissions to comment on Cloud's answer – venkata Nov 06 '17 at 17:00
0

Try this to calculate time difference between two times.

first it will convert 12 hours time into 24 hours then it will take diff between two times

String a = "09/06/18 01:55:33 AM";
            String b = "07/06/18 05:45:33 PM";
            String [] b2 = b.split(" ");
            String [] a2 = a.split(" ");
            SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm:ss");
            SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
            String time1 = null ;
            String time2 = null ;
            if ( a.contains("PM") && b.contains("AM")) {
                 
                 Date date = parseFormat.parse(a2[1]+" PM");
                 time1 = displayFormat.format(date);
                 time2 = b2[1];
            }else if (b.contains("PM") && a.contains("AM")) {
                Date date = parseFormat.parse(a2[1]+" PM");
                time1 = a2[1];
                time2 = displayFormat.format(date);
            }else if (a.contains("PM") && b.contains("PM")){
                Date datea = parseFormat.parse(a2[1]+" PM");
                Date dateb = parseFormat.parse(b2[1]+" PM");
                time1 = displayFormat.format(datea);
                time2 = displayFormat.format(dateb);
            }   
            System.out.println(time1);
            System.out.println(time2);      
            SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
            Date date1 = format.parse(time1);
            Date date2 = format.parse(time2);
            long difference = date2.getTime() - date1.getTime(); 
            System.out.println(difference);
            System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm"));

For More Details Click Here

Community
  • 1
  • 1
  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Oct 17 '18 at 18:48
  • Why the text conversions and the time diff? They are completely unrelated to the question. – aled Jul 25 '19 at 23:00
0

This is the extract of code that I have done.

    String s="08:10:45";
    String[] s1=s.split(":");
    int milipmHrs=0;
    char[] arr=s1[2].toCharArray();
    boolean isFound=s1[2].contains("PM");
    if(isFound){
        int pmHrs=Integer.parseInt(s1[0]);
        milipmHrs=pmHrs+12;
        return(milipmHrs+":"+s1[1]+":"+arr[0]+arr[1]);
    }
    else{

        return(s1[0]+":"+s1[1]+":"+arr[0]+arr[1]);
    }
  • 1
    While this code may answer the question, it would be better to explain how it solves the problem without introducing others and why to use it. Code-only answers are not useful in the long run. – Tiago Martins Peres Oct 17 '18 at 15:48
  • This is not a good solution. It is much better to use library functions and they cover more border cases. For starters your code assumes the time is a string, which is a bad assumption. Then contains() is case sensitive. – aled Jul 25 '19 at 23:03
0
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;

public class Main {
   public static void main(String [] args){
       try {
            DateFormat parseFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
            String sDate = "22-01-2019 9:0:0 PM";
            Date date = parseFormat.parse(sDate);
            SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            sDate = displayFormat.format(date);
            LOGGER.info("The required format : " + sDate);
           } catch (Exception e) {}
      }
}
  • 2
    Thank you for wanting to contribute. 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`. Also, are you contributing anything that isn’t already in some of the other answers? Finally, for others to learn from your answer, I believe that explanation is more important than code. – Ole V.V. Jan 22 '19 at 13:33
0

I have written a simple utility function.

public static String convert24HourTimeTo12Hour(String timeStr) {
    try {
        DateFormat inFormat = new SimpleDateFormat( "HH:mm:ss");
        DateFormat outFormat = new SimpleDateFormat( "hh:mm a");
        Date date = inFormat.parse(timeStr);
        return outFormat.format(date);
    }catch (Exception e){}

    return "";
}
Asad Ali Choudhry
  • 4,985
  • 4
  • 31
  • 36
0

Try this below code,

public static String timeConversion(String s) {    
        String militaryTime = "";     
        String hourString = s.substring(0,2);
        String timeFormat = s.substring(8,10);
        String timeBody = s.substring(2,8);
        
        if (timeFormat.equals("AM")){
            if (hourString.equals("12")){
                militaryTime = "00" + timeBody;
            }else{
                militaryTime = hourString + timeBody;
            }
        }else if (timeFormat.equals("PM")){
            if (hourString.equals("12")){
                militaryTime = hourString + timeBody;
            }else{
                int value = Integer.parseInt(hourString) + 12;
                militaryTime = String.valueOf(value) + timeBody;
            }
        }
        return militaryTime;
}
Anil Nivargi
  • 1,473
  • 3
  • 27
  • 34
MichealCob
  • 39
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 12 '21 at 12:57
0

Without using library methods

public static String timeConversion(String s) {
    String[] timeElements = s.split(":");
    if (s.contains("PM")) {
        timeElements[0] = getPMHours(timeElements[0]);
    } else {
        timeElements[0] = getAMHours(timeElements[0]);
    }
    timeElements[2] = timeElements[2].substring(0,2);
    return timeElements[0]+":"+timeElements[1]+":"+timeElements[2];
}
private static String getAMHours(String hour) {
    if(Integer.parseInt(hour) == 12) return "00";
    return hour;
}
private static String getPMHours(String hour) {
    int i = Integer.parseInt(hour);
    if(i != 12) return 12+i+"";
    return i+"";
}
-1

I was looking for same thing but in number, means from integer xx hour, xx minutes and AM/PM to 24 hour format xx hour and xx minutes, so here what i have done:

private static final int AM = 0;
private static final int PM = 1;
/**
   * Based on concept: day start from 00:00AM and ends at 11:59PM, 
   * afternoon 12 is 12PM, 12:xxAM is basically 00:xxAM
   * @param hour12Format
   * @param amPm
   * @return
   */
  private int get24FormatHour(int hour12Format,int amPm){
    if(hour12Format==12 && amPm==AM){
      hour12Format=0;
    }
    if(amPm == PM && hour12Format!=12){
      hour12Format+=12;
    }
    return hour12Format;
  }`

    private int minutesTillMidnight(int hour12Format,int minutes, int amPm){
        int hour24Format=get24FormatHour(hour12Format,amPm);
        System.out.println("24 Format :"+hour24Format+":"+minutes); 
        return (hour24Format*60)+minutes;
      }
RQube
  • 954
  • 3
  • 13
  • 28
-5

We can solve this by using String Buffer String s;

static String timeConversion(String s) {
   StringBuffer st=new StringBuffer(s);
   for(int i=0;i<=st.length();i++){

       if(st.charAt(0)=='0' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '3');
       }else if(st.charAt(0)=='0' && st.charAt(1)=='2' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '4');
        }else if(st.charAt(0)=='0' && st.charAt(1)=='3' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '5');
         }else if(st.charAt(0)=='0' && st.charAt(1)=='4' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '6');
         }else if(st.charAt(0)=='0' && st.charAt(1)=='5' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '7');
         }else if(st.charAt(0)=='0' && st.charAt(1)=='6' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '8');
         }else if(st.charAt(0)=='0' && st.charAt(1)=='7' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '9');
         }else if(st.charAt(0)=='0' && st.charAt(1)=='8' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '2');
                st.setCharAt(1, '0');
         }else if(st.charAt(0)=='0' && st.charAt(1)=='9' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '2');
                st.setCharAt(1, '1');
         }else if(st.charAt(0)=='1' && st.charAt(1)=='0' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '2');
                st.setCharAt(1, '2');
         }else if(st.charAt(0)=='1' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '2');
                st.setCharAt(1, '3');
         }else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='A'  ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '0');
                st.setCharAt(1, '0');
         }else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='P'  ){
                st.setCharAt(0, '1');
                st.setCharAt(1, '2');
         }
         if(st.charAt(8)=='P'){
             st.setCharAt(8,' ');

         }else if(st.charAt(8)== 'A'){
             st.setCharAt(8,' ');
         }
         if(st.charAt(9)=='M'){
             st.setCharAt(9,' ');
         }
   }
   String result=st.toString();
   return result;
}