Java的日期格式化經常使用方法

字母 日期或時間元素 表示 示例
G Era 標誌符 Text AD
y Year 199696
M 年中的月份 Month JulyJul07
w 年中的週數 Number 27
W 月份中的週數 Number 2
D 年中的天數 Number 189
d 月份中的天數 Number 10
F 月份中的星期 Number 2
E 星期中的天數 Text TuesdayTue
a Am/pm 標記 Text PM
H 一天中的小時數(0-23) Number 0
k 一天中的小時數(1-24) Number 24
K am/pm 中的小時數(0-11) Number 0
h am/pm 中的小時數(1-12) Number 12
m 小時中的分鐘數 Number 30
s 分鐘中的秒數 Number 55
S 毫秒數 Number 978
z 時區 General time zone Pacific Standard TimePSTGMT-08:00
Z 時區 RFC 822 time zone -0800

 

如下示例顯示瞭如何在美國語言環境中解釋日期和時間模式。給定的日期和時間爲美國太平洋時區的本地時間 2001-07-04 12:08:56。
日期和時間模式 結果
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700

經常使用構造方法 :html

 SimpleDateFormat sFormat = new SimpleDateFormat(String pattern);java

或者api

SimpleDateFormat sFormat = new SimpleDateFormat();app

sFormat.applyPattern(String pattern); 測試

或者spa

DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault());code

 

 

3.示例代碼 (這裏使用了log4j,只需將代碼中的log.info改爲相應的System.out.println,置於main()方法中運行便可)component

複製代碼
public void testCalendar(){
        Calendar c1 = Calendar.getInstance();
        c1.setTime(new Date());
        
        //當Calendar中設置的時間超過每項的最大值時,會以減去最大值後的值設置時間,例如月份設置13,最後會變成13-11=02
        Calendar c2 = Calendar.getInstance();
        c2.set(1920, 13, 24, 22, 32, 22);
        //使用pattern
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd H:m:s");
        SimpleDateFormat format2 = new SimpleDateFormat("yy-MM-dd H:m:s");
        SimpleDateFormat format3 = new SimpleDateFormat("y-M-d H:m:s");
        //使用約定格式
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault());

 

        //獲取Calendar中各個屬性字段的方法
        log.info("The year now time is " + c1.get(c1.YEAR));
        log.info("The month now time is " + c1.get(c1.MONTH));
        log.info("The day_of_month now time is " + c1.get(c1.DAY_OF_MONTH));
        log.info("The day_of_week now time is " + c1.get(c1.DAY_OF_WEEK));
        log.info("今天是在這個月的第幾個星期: " + c1.get(c1.DAY_OF_WEEK_IN_MONTH));
        log.info("The day_of_year now time is " + c1.get(c1.DAY_OF_YEAR));
        //不一樣模式對應的格式略有不一樣,有時間能夠測試多一點模式
        log.info("yyyy-MM-dd H:m:s-->" + format.format(c1.getTime()));
        log.info("yy-MM-dd H:m:s-->" + format2.format(c1.getTime()));
        log.info("y-M-d H:m:s-->" + format3.format(c1.getTime()));
  log.info("DateFormat.FULL-->" + dateFormat.fomat(c1.getTime()));

        log.info(format.format(c2.getTime()));orm

}
相關文章
相關標籤/搜索