使用 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
廣告