以下是日期格式模式中使用的字元。
| 編號 | 字母 | 描述 |
|---|---|---|
| 1 | G | 用於顯示時代。 |
| 2 | y | 顯示年份。 有效值為:yy,yyyy。 |
| 3 | M | 顯示月份。 有效值為:MM,MMM或MMMMM。 |
| 4 | d | 顯示月份中的第幾天。 有效值為:d,dd。 |
| 5 | h | 顯示一天中的小時(1-12 AM/PM)。 有效值為:hh。 |
| 6 | H | 顯示一天中的小時(0-23)。 有效值為:HH。 |
| 7 | m | 顯示分鐘(0-59)。 有效值為:mm。 |
| 8 | s | 顯示秒鐘(0-59)。 有效值為:ss。 |
| 9 | S | 顯示毫秒(0-999)。 有效值為:SSS。 |
| 10 | E | 顯示星期幾(例如:星期一,星期二等) |
| 11 | D | 顯示每年的日期(1-366)。 |
| 12 | F | 顯示月份中的星期幾(例如12月的第一個星期四)。 |
| 13 | w | 顯示每年的周(1-53)。 |
| 14 | W | 顯示月份中的星期(0-5) |
| 15 | a | 顯示為:AM或PM |
| 16 | k | 在一天中顯示小時(1-24)。 |
| 17 | K | 要顯示小時,AM / PM(0-11)。 |
| 18 | z | 顯示時區。 |
在這個例子中,我們根據不同的模式格式化日期。
檔:IOTester.java -
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class I18NTester {
public static void main(String[] args) throws ParseException {
String pattern = "dd-MM-yy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = new Date();
System.out.println(simpleDateFormat.format(date));
pattern = "MM-dd-yyyy";
simpleDateFormat = new SimpleDateFormat(pattern);
System.out.println(simpleDateFormat.format(date));
pattern = "yyyy-MM-dd HH:mm:ss";
simpleDateFormat = new SimpleDateFormat(pattern);
System.out.println(simpleDateFormat.format(date));
pattern = "EEEEE MMMMM yyyy HH:mm:ss.SSSZ";
simpleDateFormat = new SimpleDateFormat(pattern);
System.out.println(simpleDateFormat.format(date));
}
}
執行上面示例代碼,得到以下結果 -
29-11-17
11-29-2017
2017-11-29 18:47:42
Wednesday November 2017 18:47:42.787+0530
