Sunday 21 August 2022

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

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

 

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



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 = "08-21-2022 20:30:22";

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

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

            final Date date = dateFormat.parse(dateStr);

            final String output = outputformat.format(date);

            System.out.println(output);
      }
}

 

Output

21/08/2022 08:30:22 pm

 

Reference

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

 

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment