前言
Date表示特定的瞬间,精确到毫秒。它允许把日期解释为年、月、日、小时、分钟和秒值;它也允许格式化和解析日期字符串; Calendar类是一个抽象类,时间操作类,由于Date类过于古老,许多的构造器和方法都已经过时,已经满足不了需求。 因此Java推荐使用Calendar来完成时间计算等操作。 它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等日历字段之间的转换提供了一些方法,并为操作日历字段 。
注意区别:Date是日期数据,Calendar是数据操作类。
Date
创建对象
//创建了一个Date对象,代表当前时间
Date date1 = new Date();
常用方法
- getTime()
//从1970-0-0年到创建Date对象的的毫秒数
System.out.println(date1.getTime());
- 比较两个date对象的大小,afer和before和compareTo
Date date2 = new Date(date1.getTime()-1000);
System.out.println(date1.after(date2));//判断date1是否在date2的之后
System.out.println(date1.before(date2));//判断date1是否在date2的之前
//比较时间大小。大于返回1,相等返回0,小于返回-1
System.out.println(date1.compareTo(date2));
Calendar
创建对象
//当前时间的calendar对象
Calendar calendar = Calendar.getInstance();
get
月份的正常值范围为0-11,0表示一月,以此类推。星期是从星期天开始计算,星期天为1,以此类推。日期的正常值范围为1-31,结尾数字视月份而定d
System.out.println("获取calendar的年份"+calendar.get(Calendar.YEAR));
System.out.println("获取calendar月份,从零开始"+calendar.get(Calendar.MONTH));
System.out.println("获取星期,从星期天开始"+calendar.get(Calendar.DAY_OF_WEEK));
System.out.println("获取今天是多少号"+calendar.get(Calendar.DATE));
System.out.println("这个月的第几星期"+calendar.get(Calendar.WEEK_OF_MONTH));
System.out.println("今年的第几星期"+calendar.get(Calendar.WEEK_OF_YEAR));
getTime()要注意,Date也有这个方法,两者的用法是完全不同的。
System.out.println(calendar.getTime());//将calendar变为date
set
语法
set(int field, int value);
set(int year, int month, int day);
set(int year, int month, int day, int hour, int minute);
set(int year, int month, int day, int hour, int minute, int second);
设置年、月、日、时、分、秒、毫秒
案例
Calendar calendar = Calendar.getInstance();
calendar.set(2019,2,23);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("通过set的"+simpleDateFormat.format(calendar.getTime()));
三个常用的场景
一、格式化输出时间
Date--->String format
Date date = new Date();
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String result = simpleDateFormat1.format(date);//将日期转换为String
System.out.println(result);
String----->Date perse
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
String result="2005-8-18 14:21:12.123";
Date date = simpleDateFormat.parse(result);
System.out.println(simpleDateFormat.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
二、Date和Calendar的转换
Calendar---->Date getTime()
Calendar cal=Calendar.getInstance();
Date date=cal.getTime();
Date----->Clendar
Date date=new Date();
Calendar cal=Calendar.getInstance();
cal.setTime(date);
三、String和Date和Long之间的转换
字符串转化成时间类型(字符串可以是任意类型,只要和SimpleDateFormat中的格式一致即可)
通常我们取时间跨度的时候,会substring出具体时间--long-比较
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("M/dd/yyyy hh:mm:ss a",java.util.Locale.US);
java.util.Date d = sdf.parse("5/13/2003 10:31:37 AM");
long dvalue=d.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String mDateTime1=formatter.format(d);