Java程序:AM-PM格式的时间格式化


时间格式化 是将日期和时间值转换为具有特定格式的人类可读字符串的过程。生成的字符串描述了日期/时间值应如何表示(例如平面文件或人类可读输出)。在本文中,我们将了解如何以AM-PM格式格式化时间。

在12小时制中,使用AM-PM格式来定义时间。这里,AM代表Ante meridiem(上午),而PM代表Post meridiem(下午)。

示例场景

Input: current_date = Thu Mar 17 16:04:31 IST 2024
Output: Current Time in AM/PM format is = 04.04 pm

以AM-PM格式格式化时间的方法

要以AM-PM格式格式化时间,我们可以使用以下方法:

  • 使用SimpleDateFormat类
  • 使用用户定义函数

使用SimpleDateFormat类

Java中,SimpleDateFormat类DateFormat类的子类。它提供多种方法来解析和格式化日期/时间。它允许我们为格式化目的选择任何用户定义的模式。

示例

在这个例子中,我们将使用SimpleDateFormat类的format()方法以AM-PM格式化时间。

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 2024

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

使用用户定义函数

用户定义函数中,我们将传递当前日期并使用format()方法以AM-PM格式格式化日期和时间值。程序员创建的用于执行特定任务的代码块称为用户定义函数。

示例

在这里,我们定义了一个函数来以AM-PM格式格式化日期/时间。

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 2024
The current Time in AM/PM format is : 04.04 pm

更新于:2024年8月1日

浏览量:1K+

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.