基于Java的时间转换:Date、Timestamp和String时间转化

package ZIPUtil;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

//---------String 转换 Date类型-------------------
String date1 = "2017-12-01 12:01:56"; //设定字符串时间
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//根据字符串的时间格式设定时间模板,yyyy代表“年”,MM 代表"月", dd代表“天”, HH 代表小时,mm代表分钟,ss 代表秒,SSS代表毫秒 
Date d1 = new Date(); 
try {
d1 = df1.parse(date1);//解析字符串时间
System.out.println("d1:"+d1); //输出到控制台:Fri Dec 01 12:01:56 CST 2017
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


//--------- Date转换 String类型-------------------
Date d2 = new Date(); //创建一个新的时间对象,目的获取当前的时间
DateFormat df2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//根据字符串的时间格式设定时间模板,yyyy代表“年”,MM 代表"月", dd代表“天”, HH 代表小时,mm代表分钟,ss 代表秒,SSS代表毫秒
String date2 = df2.format(d2);//将时间对象输出字符串时间
System.out.println("date2:"+date2);//字符串时间:



//------------Timestamp 和 String类型胡转-------------------
Timestamp ts = new Timestamp(System.currentTimeMillis()); 
DateFormat df3 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//根据字符串的时间格式设定时间模板,yyyy代表“年”,MM 代表"月", dd代表“天”, HH 代表小时,mm代表分钟,ss 代表秒,SSS代表毫秒

//Timestamp使用toString转化成字符串
System.out.println("toString:"+ts.toString());
//使用DateFormat转化成String
System.out.println("df3:"+df3.format(ts));


}


}

  

原文地址:https://www.cnblogs.com/lihaiming93/p/8116507.html