代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class MainProcess {
public static void main(String[] args) throws ParseException {
// 1.set format
SimpleDateFormat timeSmat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 2.date to timestamp
String myDate = "2015-01-01 00:00:00";
long parse = timeSmat.parse(myDate).getTime();
System.out.println("date to ts:" + parse);
// 3.timestamp to date
long myTs = 1420041600000L;
String format = timeSmat.format(myTs);
System.out.println("ts to date:" + format);
}
}
输出:
如果要封装成方法:
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class dateFormatUtil {
public static void main(String[] args) throws ParseException {
long time = System.currentTimeMillis();
System.out.println(time);
System.out.println(timeToFormat(time));
System.out.println(timeToSecond(timeToFormat(time)));
}
//timestamp to date
public static String timeToFormat(long time) {
SimpleDateFormat timeSmat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
return timeSmat.format(time);
}
//date to timestamp
public static long timeToSecond(String date) throws ParseException {
SimpleDateFormat timeSmat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return timeSmat.parse(date).getTime();
}
}