Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để định dạng thời gian ở định dạng AM-PM

Trong bài này, chúng ta sẽ hiểu cách định dạng thời gian ở định dạng AM-PM. Chuỗi định dạng mô tả cách đọc và ghi các giá trị ngày / giờ từ (thành) biểu diễn chuỗi (tệp phẳng, đầu ra có thể đọc được của con người, v.v.)

Dưới đây là một minh chứng về điều tương tự -

Giả sử đầu vào của chúng tôi là -

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

Đầu ra mong muốn sẽ là -

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

Thuật toán

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

Ví dụ 1

Tại đây, đầu vào đang được người dùng nhập dựa trên lời nhắc.

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);
   }
}

Đầu ra

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

Ví dụ 2

Ở đây, chúng tôi đã xác định một hàm để tính toán độ lệch chuẩn.

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);
   }
}

Đầu ra

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