Skip to Content
CoursesCSC102การแปลงเวลาจากรูปแบบ 12 ชั่วโมงเป็น 24 ชั่วโมง

การแปลงเวลาจากรูปแบบ 12 ชั่วโมงเป็น 24 ชั่วโมง

โจทย์

Neil, a member of Tenet, is assigned a mission to travel back in time using an inverted entropy to prevent some incidents. He is given a list of incidents together with a time. However, he has a 24-hour watch but the provided list indicates 12-hour time format. He need to convert the time from 12-hour format to 24-hour format in order to work with his watch. Your task is to support Neil by writing a program to convert the 12-hour time format to the 24-hour time format.

An input comprises 2 integers representing hour and minute and 1 String represents am or pm.

Note that 12:00 AM in 12-hour time format is 00:00 in 24-hour time format.

InputOutput
12 00 am00:00

โค้ด

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int hour = scanner.nextInt(); int minute = scanner.nextInt(); String suffix = scanner.next().toLowerCase(); int convertedHour = (suffix.equals("am")) ? hour % 12 : (hour % 12) + 12; System.out.printf("%02d:%02d", convertedHour, minute); } }

คำอธิบาย

1. การรับข้อมูล

Scanner scanner = new Scanner(System.in); int hour = scanner.nextInt(); // รับค่าชั่วโมง int minute = scanner.nextInt(); // รับค่านาที String suffix = scanner.next().toLowerCase(); // รับ am/pm และแปลงเป็นตัวพิมพ์เล็ก

2. การแปลงเวลา

int convertedHour = (suffix.equals("am")) ? hour % 12 : (hour % 12) + 12;

กรณี AM

  • hour % 12 จะคืนค่า 0 ถ้าเป็น 12 AM
  • คืนค่าชั่วโมงเดิมสำหรับ 1-11 AM

กรณี PM

  • (hour % 12) + 12 จะบวก 12 เข้าไปในทุกกรณียกเว้น 12 PM
  • 12 PM จะกลายเป็น 12
  • 1-11 PM จะกลายเป็น 13-23

3. การแสดงผล

System.out.printf("%02d:%02d", convertedHour, minute);
  • %02d หมายถึงแสดงตัวเลขใน 2 หลัก เติม 0 ข้างหน้าถ้าจำเป็น

แผนภาพการทำงาน

ปรับปรุงล่าสุด