Date()
public Date()分配 Date 对象并初始化此对象,以表示分配它的时间(精确到毫秒)。
SimpleDateFormat()
例子1:
package cn.edut.tarena.demo1;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
public class Demo_Date {
@Test
public void test001() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = "2019-11-12";
Date d = null;
try {
d = sdf.parse(date) ;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(d.toLocaleString());
}
}
例子2:计算间隔天数
/** * 计算存活天数 */
@Test
public void test002() {
String birthday = "2018-11-11";
System.out.println(birthday);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
long millionSecond = -1;
try {
millionSecond = countMillionSecondToNow(sdf.parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("已存活millionSecond:"+millionSecond);
System.out.println("已存活天数:"+millionSecond/(1000*60*60*24));
}
public long countMillionSecondToNow(Date startDate) {
return System.currentTimeMillis()-startDate.getTime();
}