Timestamp,Date和String的互相转换

 

1.Timestamp,Date和String的互相转换

//Timestamp转换成String:
Timestamp ts = new Timestamp(System.currentTimeMillis());
String tsStr = "";
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
    // 方法一
    tsStr = sdf.format(ts);
    System.out.println(tsStr);
    // 方法二
    tsStr = ts.toString();
    System.out.println(tsStr);
} catch (Exception e) {
    e.printStackTrace();
}

// String转换成Timestamp:
Timestamp ts = new Timestamp(System.currentTimeMillis());
String tsStr = "2011-05-09 11:49:45";
try {
    ts = Timestamp.valueOf(tsStr);
    System.out.println(ts);
} catch (Exception e) {
    e.printStackTrace();
}

// Date转换成String:
String dateStr = "";
Date date = new Date();
// format的格式可以任意
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH/mm/ss");
try {
    dateStr = sdf.format(date);
    System.out.println(dateStr);
    dateStr = sdf2.format(date);
    System.out.println(dateStr);
} catch (Exception e) {
    e.printStackTrace();
}

// String转换成Date:
String dateStr = "2010/05/04 12:34:23";
Date date = new Date();
// 注意format的格式要与日期String的格式相匹配
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
    date = sdf.parse(dateStr);
    System.out.println(date.toString());
} catch (Exception e) {
    e.printStackTrace();
}

2.Calendar的用法(已有的的Timestamp对象expiration值减掉5年,返回给createdate对象)

Calendar c = Calendar.getInstance();
c.setTime(expiration);
c.add(Calendar.YEAR,-5);
Timestamp createdate = new Timestamp(c.getTimeInMillis());

 

posted @ 2016-02-25 15:44  风归云隐  阅读(14933)  评论(0编辑  收藏  举报