Home String、Date、Timestamp之间的转换
Post
Cancel

String、Date、Timestamp之间的转换

一、String与Date互转

1.1 String转Date

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {
    // 注意format的格式要与日期String的格式相匹配 
    DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    String dateStr = "2010/05/04 12:34:23";
    Date date = new Date();
    try {
        date = sdf.parse(dateStr);
        System.out.println(date.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

1.2 Date转String

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {
    //format的格式可以任意  
    DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
    DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH/mm/ss");  
    Date date = new Date();  
    try {  
        System.out.println(sdf.format(date));  
        System.out.println(sdf2.format(date));  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}

二、String与Timestamp互转

2.1 String转Timestamp

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {
    Timestamp ts = new Timestamp(System.currentTimeMillis());  
    // String的类型必须形如: yyyy-mm-dd hh:mm:ss[.f...]
    // 这样的格式,中括号表示可选,否则报错
    String tsStr = "2011-05-09 11:49:45";  
    try {  
        ts = Timestamp.valueOf(tsStr);  
        System.out.println(ts);  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}

2.2 Timestamp转String

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {
    DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Timestamp ts = new Timestamp(System.currentTimeMillis());
    try {
        // 方法一,优势在于可以灵活的设置字符串的形式
        System.out.println(sdf.format(ts));
        // 方法二
        System.out.println(ts.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

三、Date与Timestamp互转

3.1 Timestamp转Date

1
2
3
4
5
6
7
8
9
10
public static void main(String[] args) {
    Timestamp ts = new Timestamp(System.currentTimeMillis());
    Date date = new Date();
    try {
        date = ts;
        System.out.println(date.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Date和Timesta是父子类关系。

3.2 Date转Timestamp

1
2
3
4
5
6
7
8
9
10
public static void main(String[] args) {
    Timestamp ts = new Timestamp(System.currentTimeMillis());
    Date date = new Date();
    try {
        ts = new Timestamp(date.getTime());
        System.out.println(ts.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
This post is licensed under CC BY 4.0 by the author.