Java代碼
- 在 Java 應用中,格式化日期時間通常會用到 SimpleDateFormat 類
- public class SimpleDateFormat extends DateFormat
- SimpleDateFormat 是一個以國別敏感的方式格式化和分析數據的具體類。 它允許格式
化 (date -> text)、語法分析 (text -> date)和標準化。 - SimpleDateFormat 允
許以為日期-時間格式化選擇任何用戶指定的方式啟動。 但是,希望
用 DateFormat 中的 getTimeInstance、 getDateInstance 或 getDateTimeInstance 創
建一個日期-時間格式化程序。 每個類方法返回一個以缺省格式化方式初始化的日期/時間格式化程序。 可以根據需要用 applyPattern 方法修
改格式化方式。 - SimpleDateFormat
函數的繼承關系: - java.lang.Object
- |
- —-java.text.Format
- |
- —-java.text.DateFormat
- |
- —-java.text.SimpleDateFormat
- 下面是個小例子:
- import java.text.*;
- import java.util.Date;
- /**
- SimpleDateFormat
函數語法: - G 年代標志符
- y 年
- M 月
- d 日
- h 時 在上午或下
午 (1~12) - H 時 在一天
中 (0~23) - m 分
- s 秒
- S 毫秒
- E 星期
- D 一年中的第幾天
- F 一月中第幾個星期幾
- w 一年中第幾個星期
- W 一月中第幾個星期
- a 上午 / 下午 標
記符 - k 時 在一天
中 (1~24) - K 時 在上午或下
午 (0~11) - z 時區
- */
- public class FormatDateTime {
- public static void main(String[] args) {
- SimpleDateFormat myFmt=new SimpleDateFormat(“yyyy年MM月dd日 HH時mm分ss秒”);
- SimpleDateFormat myFmt1=new SimpleDateFormat(“yy/MM/dd HH:mm”);
- SimpleDateFormat myFmt2=new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);//等價於now.toLocaleString()
- SimpleDateFormat myFmt3=new SimpleDateFormat(“yyyy年MM月dd日 HH時mm分ss秒 E “);
- SimpleDateFormat myFmt4=new SimpleDateFormat(
- “一年中的第 D 天 一年中第w個星期 一月中第W個星期 在一天中k時 z時區”);
- Date now=new Date();
-