使用 SimpleDateFormat 類格式化日期

來源:互聯網
上載者:User

你可以使用 SimpleDateFormat 類,如果日期格式不對,會產生異常。

import java.text.*;
import java.util.*;

public class TestDate {
    public static void main(String[] args) {
        String dStr = "2001.12.12-08.23.21";
        Date d = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd-HH.mm.ss");
        try {
            d = sdf.parse(dStr);
        } catch (ParseException pe) {
            System.out.println(pe.getMessage());
        }
        System.out.println(d);
        System.out.println(d.getTime());
    }
}

在 java.text 包中找到那個 SimpleDateFormat 類,給它一個模板,可以 parse 成一個 Date,然後使用 Date 類的 getItme() 方法,可以得到一個 Long 資料。

模板定義如下:
y        年號,如 1996
M        月份,如 July 或者 07
d        月中第幾天,如 12
H        小時(24制),如 0、17
m        分鐘,如 32
s        鈔鐘,如55
S        微鈔,如978
E        星期幾,如 Tuesday
D        一年中的第幾天,如 189
w        week in year            (Number)            27
W        week in month          (Number)            2
a        am/pm marker            (Text)              PM
k        hour in day (1~24)      (Number)            24
K        hour in am/pm (0~11)    (Number)            0
z        time zone              (Text)              Pacific Standard Time
'        escape for text        (Delimiter)
''      single quote            (Literal)          '

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.