Java Program to Format time in AM-PM format

JavaCampus InterviewServer Side ProgrammingProgramming

In this article, we will understand how to format time in AM-PM format. A formatting string describes how a date/time values should be read and written from(to) string representation (flat files, human readable output, etc.)

Below is a demonstration of the same −

Suppose our input is

Current date: Thu Mar 17 16:04:31 IST 2022

The desired output would be

The current Time in AM/PM format is : 04.04 pm

Algorithm

Step 1 - START
Step 2 - Declare a date object namely current_date that fetches the current date and time.
Step 3 - Define the values.
Step 4 - Declare an object ‘formatTime’ of class SimpleDateFormat.
Step 5 - Use the function .format(current_date) to format the time to the specified format.
Step 6 - Display the result
Step 7 - Stop

Example 1

Here, the input is being entered by the user based on a prompt.

import java.util.Date;
import java.text.SimpleDateFormat;
public class Demo {
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      Date current_date = new Date();
      System.out.println("The current date is: " + current_date);
      SimpleDateFormat formatTime = new SimpleDateFormat("hh.mm aa");
      String result_time = formatTime.format(current_date);
      System.out.println("\nThe current Time in AM/PM format is : " + result_time);
   }
}

Output

The required packages have been imported
The current date is: Thu Mar 17 16:04:31 IST 2022

The current Time in AM/PM format is : 04.04 pm

Example 2

Here, we have defined a function to compute the standard deviation.

import java.util.Date;
import java.text.SimpleDateFormat;
public class Demo {
   static void format_time(Date current_date){
      SimpleDateFormat formatTime = new SimpleDateFormat("hh.mm aa");
      String result_time = formatTime.format( current_date);
      System.out.println("\nThe current Time in AM/PM format is : " + result_time);
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      Date current_date = new Date();
      System.out.println("The current date is: " + current_date);
      format_time(current_date);
   }
}

Output

The required packages have been imported
The current date is: Thu Mar 17 16:04:31 IST 2022

The current Time in AM/PM format is : 04.04 pm
raja
Updated on 30-Mar-2022 06:36:20

Advertisements