Date: 日期对象. 常用
常用场景:
获取系统当前时间:
将日期转换成需要的字符串格式:
获取一个指定日期的日期对象:
获取日期对象的总毫秒数: 保证时间数据在数据库中存储的精度
总毫秒数的计算方式: 从1970年1月1日00:00:00开始计算. 格林威治时间
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 测试类, Date
* @author Administrator
*
*/
public class Test4 {
public static void main(String[] args) {
// 获取系统当前时间:
Date now = new Date();
System.out.println(now);
// 将日期转换成需要的字符串格式:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
System.out.println(sdf.format(now));
// 获取一个指定日期的日期对象:
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
Date birthday = null;
try {
birthday = sdf2.parse("1990-5-30");
System.out.println(birthday);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("-----------------------------------------");
System.out.println("年:" + (now.getYear()+1900)); // 从1900开始计算
System.out.println("月:" + (now.getMonth()+1)); // 范围: 0 ~ 11
System.out.println("日:" + now.getDate());
System.out.println("时:" + now.getHours());
System.out.println("分:" + now.getMinutes());
System.out.println("秒:" + now.getSeconds());
System.out.println("星期几:" + now.getDay()); //范围: 0 ~ 6
System.out.println("-----------------------------------------");
//使用构造方法指定日期:
// Date hireDate = new Date(2010-1900, 10-1, 8);
Date hireDate = new Date(2010-1900, 10-1, 8, 14, 10);
// Date hireDate = new Date(2010-1900, 10-1, 8, 14, 10, 25);
System.out.println(hireDate);
Date registeTime = new Date(0);
System.out.println(registeTime);
System.out.println(new Date(643993200000L));//长整型
// 获取日期对象的总毫秒数:
System.out.println(now.getTime());
System.out.println(birthday.getTime());
System.out.println(hireDate.getTime());
}
}