ในบทความนี้ เราจะเข้าใจวิธีการจัดรูปแบบเวลาในรูปแบบ AM-PM สตริงการจัดรูปแบบอธิบายวิธีการอ่านและเขียนค่าวันที่/เวลาจาก (ถึง) การแสดงสตริง (ไฟล์แบบเรียบ เอาต์พุตที่มนุษย์อ่านได้ ฯลฯ)
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
สมมติว่าข้อมูลที่เราป้อนคือ −
Current date: Thu Mar 17 16:04:31 IST 2022
ผลลัพธ์ที่ต้องการจะเป็น −
The current Time in AM/PM format is : 04.04 pm
อัลกอริทึม
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
ตัวอย่างที่ 1
ที่นี่ ผู้ใช้ป้อนอินพุตตามข้อความแจ้ง
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);
}
} ผลลัพธ์
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
ตัวอย่างที่ 2
ในที่นี้ เราได้กำหนดฟังก์ชันเพื่อคำนวณค่าเบี่ยงเบนมาตรฐาน
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);
}
} ผลลัพธ์
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