Sunday 21 August 2022

Java: Convert time from 12 hour format to 24 hour format

Using SimpleDateFormat, we can convert the time from 12 hour format to 24 hour format. Just for your reference, patterns letter ‘a’ is used to represent AM/PM marker.

 

Below program convert the input "21/8/2022 8:30:22 PM" to "08-21-2022 20:30:22"

 


TimeConversion.java

package com.sample.app;

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

public class TimeConversion {

      public static void main(String[] args) throws ParseException {
            final String dateStr = "21/8/2022 8:30:22 PM";

            final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");

            final DateFormat outputformat = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");

            final Date date = dateFormat.parse(dateStr);

            final String output = outputformat.format(date);

            System.out.println(output);
      }
}

Output

08-21-2022 20:30:22

 

 

 

Reference

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html


  

Previous                                                 Next                                                 Home

No comments:

Post a Comment