使用 SimpleDateFormat 格式化日期的 Java 程式


SimpleDateFormat 類用於解析和格式化日期。要建立一個物件,請首先匯入以下包

import java.text.SimpleDateFormat;

設定日期

String strDate = "'Year = '";
strDate += "yyyy";
strDate += "'
Month = '"; strDate += "MMMMMMMMM"; strDate += "'
Hours = '"; strDate += "hh"; strDate += "a"; strDate += "'
Minutes = '"; strDate += "mm"; strDate += "'
Seconds = '"; strDate += "ss";

現在,建立一個物件並格式化日期 −

SimpleDateFormat dateFormat = new SimpleDateFormat(strDate);
String formattedDate = dateFormat.format(new Date());

以下是一個示例 −

示例

 即時演示

import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
   public static void main(String args[]) {
      String strDate = "'Year = '";
      strDate += "yyyy";
      strDate += "'
Month = '";       strDate += "MMMMMMMMM";        strDate += "'
Hours = '";       strDate += "hh";       strDate += "a";       strDate += "'
Minutes = '";       strDate += "mm";       strDate += "'
Seconds = '";       strDate += "ss";       System.out.println("Date and Time....");       SimpleDateFormat dateFormat = new SimpleDateFormat(strDate);       String formattedDate = dateFormat.format(new Date());       System.out.println(formattedDate);    } }

輸出

Date and Time....
Year = 2018
Month = November
Hours = 09AM
Minutes = 12
Seconds = 41

更新日期: 27-6 月-2020

206 人瀏覽

開啟您的職業生涯

完成課程後獲得認證

開始
廣告