前言
在JDK1.8之前Java提供了java.util.Date和Calendar处理日期,但是也存在了许多问题。如对象的属性可以通过方法修改;Date中的年份从1990开始,而月份从0开始;只能通过Date类格式化;这两个类不是线程安全的等等。
在JDK1.8中引入了java.time,吸收了Joda-Time的精华,其中包含了所有关于本地日期(LocalDate)、本地时间(LocalTime)、本地日期时间(LocalDateTime)、时区(ZonedDateTime)和持续时间(Duration)的类。而Date类新增了toInstant()方法,用于把Date转换成新的表达方式
1. java.lang.System类
System类提供的public static long currentTimeMillis()用来返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差,称为时间戳
示例
@Test
public void currentTimeMillisTest(){
long time = System.currentTimeMillis();
System.out.println(time);
}
2. java.util.Date类
表示特定的瞬间,精确到毫秒
2.1 构造器
/**
* Allocates a <code>Date</code> object and initializes it so that
* it represents the time at which it was allocated, measured to the
* nearest millisecond.
*
* @see java.lang.System#currentTimeMillis()
* 使用无参构造器创建的对象可以获取本地当前时间
*/
public Date() {
this(System.currentTimeMillis());
}
/**
* Allocates a <code>Date</code> object and initializes it to
* represent the specified number of milliseconds since the
* standard base time known as "the epoch", namely January 1,
* 1970, 00:00:00 GMT.
*
* @param date the milliseconds since January 1, 1970, 00:00:00 GMT.
* @see java.lang.System#currentTimeMillis()
*/
public Date(long date) {
fastTime = date;
}
2.2 常用方法
/**
* 返回自1970年1月1日00:00:00 GMT以来此Date对象表示的毫秒数
* Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by this <tt>Date</tt> object.
*
* @return the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by this date.
*/
public long getTime() {
return getTimeImpl();
}
/**
* 把此Date对象转换为以下形式的String:dow mon dd hh:mm:ss zzz yyyy
* 其中:dow是一周中的某一天(Sun,Mon,Tue,Wed,Thu,Fri,Sat),zzz是时间标准
* @return a string representation of this date.
* @see java.util.Date#toLocaleString()
* @see java.util.Date#toGMTString()
*/
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == BaseCalendar.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
示例
@Test
public void utilDateTest(){
//构造器一:Date() 创建一个对应当前时间的Date对象
Date date1 = new Date();
//获取当前Date对象对应的时间戳
System.out.println(date1.getTime());
//获取当前的年、月、日、时、分、秒
System.out.println(date1.toString());
//构造器二:创建指定毫秒数的Date对象
Date date2 = new Date(1603025970945L);
System.out.println(date2.toString());
}
3. java.sql.Date类
对应着数据库中的日期类型的变量
@Test
public void sqlDateTest(){
//创建java.sql.Date对象
java.sql.Date date = new java.sql.Date(1603025970945L);
System.out.println(date);
//将java.util.Date对象转换为java.sql.Date对象
//情况一
Date date1 = new java.sql.Date(1603025970945L);
java.sql.Date date2 = (java.sql.Date) date1;
//情况二
Date date3 = new Date();
java.sql.Date date4 = new java.sql.Date(date3.getTime());
}
3.1 日期格式转换
3.1.1 Date转String
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
System.out.println(dateString);
3.1.2 String转Date
String dateString = "2020年10月18日";
DateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
Date date = format.parse(dateString);
System.out.println(date.toString());
4. Calender类
Calendar类是一个抽象类,无法直接创建对象使用。Calendar实例化的两种方式,一是创建其子类GregorianCalendar的对象,二是调用其静态方法getInstance()。static Calendar getInstance()使用默认时区和语言环境获得一个日历。
4.1 实例化
//方式一:创建其子类(GregorianCalendar)的对象
GregorianCalendar gregorianCalendar = new GregorianCalendar();
//方式二:调用其静态方法getInstance()
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getClass());
4.2 常用方法
/*public int get(int field)
返回给定日历字段的值*/
//示例:获取日期是这个月的第几天
int days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);
/*public void set(int field, int value)
将给定的日历字段设置为给定值*/
//示例:将日历中的天数修改为1号
calendar.set(Calendar.DAY_OF_MONTH,1);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);
/*abstract void add(int field, int amount)
根据日历的规则,为给定的日历字段添加或减去指定的时间量*/
//示例:将日历中的天数加3
calendar.add(Calendar.DAY_OF_MONTH,3);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);
/*public final Date getTime()
返回一个表示此Calendar时间值(从历元到现在的亳秒偏移量)的Date对象*/
Date date = calendar.getTime();
System.out.println(date);
/*public final void setTime(Date date)
使用此Calendar的指定Date设置时间*/
Date date1 = new Date();
calendar.setTime(date1);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);
5. LocalDate、LocalTime、LocalDateTime的使用
//实例化 获取当前的日期时间
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate);
System.out.println(localTime);
System.out.println(localDateTime);
//of() 设置指定的时间
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
System.out.println(localDateTime1);
//getXxx() 获取相关属性
System.out.println(localDateTime.getDayOfMonth());
System.out.println(localDateTime.getDayOfWeek());
//withXxx() 设置相关属性
LocalDate localDate1 = localDate.withDayOfMonth(22);
System.out.println(localDate);
System.out.println(localDate1);
LocalDateTime localDateTime2 = localDateTime.withHour(4);
System.out.println(localDateTime);
System.out.println(localDateTime2);
//不可变性 修改后返回重新new的一个对象,不会修改原来的对象
LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
System.out.println(localDateTime);
System.out.println(localDateTime3);
LocalDateTime localDateTime4 = localDateTime.minusDays(6);
System.out.println(localDateTime);
System.out.println(localDateTime4);