代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;public class MainProcess {public static void main(String[] args) throws ParseException {// 1.set formatSimpleDateFormat timeSmat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 2.date to timestampString myDate = "2015-01-01 00:00:00";long parse = timeSmat.parse(myDate).getTime();System.out.println("date to ts:" + parse);// 3.timestamp to datelong 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 datepublic static String timeToFormat(long time) {SimpleDateFormat timeSmat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式return timeSmat.format(time);}//date to timestamppublic static long timeToSecond(String date) throws ParseException {SimpleDateFormat timeSmat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return timeSmat.parse(date).getTime();}
}