String、Date、Timestamp互转

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/imHanweihu/article/details/80921482

1. String与Date互转

@Test
public void testDateString() throws ParseException {

    // string -> date
    //注意:format的格式要与日期String的格式相匹配
    String str = "2018-07-05 08:48:00";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // string -> date
    Date date = sdf.parse(str);
    System.out.println(date.toString()); // Thu Jul 05 08:48:00 CST 2018

    // date -> string
    // format格式可以任意
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); // date -> string
    String res = df.format(new Date());
    System.out.println(res); // 2018/07/05 09:00:54
}

2. String与TimeStamp互转

@Test
public void testStringTimestamp() {

    // string -> timestamp
    // 注:String的类型必须形如: yyyy-mm-dd hh:mm:ss[.f...] 这样的格式,中括号表示可选,否则报错!!!
    String str = "2018-07-05 08:48:00";
    Timestamp ts = Timestamp.valueOf(str);
    System.out.println(ts); // 2018-07-05 08:48:00.0

    // timestamp -> string
    // format格式可以任意
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); // date -> string
    Timestamp tsNow = new Timestamp(System.currentTimeMillis());
    // 方法一:df.format 可以灵活的设置格式
    String tsStr = df.format(tsNow);
    System.out.println(tsStr);  // 2018/07/05 09:21:28
    // 方法二:toString
    tsStr = tsNow.toString();
    System.out.println(tsStr); // 2018-07-05 09:21:28.958
}

3. Date与TimeStamp互转

@Test
public void testDateTimeStamp(){
    // date是timestamp的父类

    // timestamp -> date
    Timestamp tsNow = new Timestamp(System.currentTimeMillis());
    Date date = new Date(tsNow.getTime());
    System.out.println(date); // Thu Jul 05 09:27:36 CST 2018

    // date -> timestamp
    // 父类不能直接向子类转化,因此借助string
    Date dateNow = new Date();
    Timestamp ts = new Timestamp(dateNow.getTime());
    System.out.println(ts); // 2018-07-05 09:30:11.032
}

猜你喜欢

转载自blog.csdn.net/imHanweihu/article/details/80921482