1)获取当前时间(不同类型,不同方法)
public static void main(String[] args) {
//当前时间:date = 2019-09-17 16:59:23
Date date = DateUtil.date();
//当前时间:date2 = 2019-09-17 16:59:23
Date date2 = DateUtil.date(Calendar.getInstance());
//当前时间:date3 = 2019-09-17 16:59:23
Date date3 = DateUtil.date(System.currentTimeMillis());
//当前时间字符串:now = 2019-09-17 16:59:23
String now = DateUtil.now();
//当前日期字符串:today = 2019-09-17
String today= DateUtil.today();
}
2)给定时间字符串与日期格式字符串--返回指定Date类型内容
/*DateUtil.parse方法会自动识别一些常用格式,包括:
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd
HH:mm:ss
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss.SSS*/
//这四种情况均可以转换,并且输出结果均为: 2019-09-17 00:00:00
Date date1 = DateUtil.parse("2019-09-17");
Date date2 = DateUtil.parse("2019-09-17", "yyyy-MM-dd");
Date date3 = DateUtil.parse("2019/09/17", "yyyy/MM/dd");
Date date4 = DateUtil.parse("2019:09:17", "yyyy:MM:dd");
3)Date与String之间的格式化转换
Date date1 = DateUtil.parse("2019-09-17");
//结果: 2019/09/17
String format = DateUtil.format(date1, "yyyy/MM/dd");
//常用格式的格式化,结果:2017-03-01
String formatDate = DateUtil.formatDate(date1);
//结果:2019-09-17 00:00:00
String formatDateTime = DateUtil.formatDateTime(date1);
//结果:00:00:00
String formatTime = DateUtil.formatTime(date1);
4)获取Date对象的某个部分
Date date = DateUtil.date();
//获得年的部分:year = 2019
int year = DateUtil.year(date);
//获得月份,从0开始计数:month = 8
int month = DateUtil.month(date);
//获得月份枚举 :monthEnum = SEPTEMBER
Month monthEnum = DateUtil.monthEnum(date);
5)开始和结束时间
String now = DateUtil.now();
Date date = DateUtil.parse(now);
//一天的开始,结果:2019-09-17 00:00:00
Date beginOfDay = DateUtil.beginOfDay(date);
//一天的结束,结果:2019-09-17 23:59:59
Date endOfDay = DateUtil.endOfDay(date);
6)日期时间偏移
String now = DateUtil.now();
//date = 2019-09-17 17:35:35
Date date = DateUtil.parse(now);
//结果:newDate = 2019-09-19 17:35:35
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
//常用偏移,结果:newDate2 = 2019-09-20 17:35:35
DateTime newDate2 = DateUtil.offsetDay(date, 3);
//常用偏移,结果:newDate3 = 2019-09-17 14:35:35
DateTime newDate3 = DateUtil.offsetHour(date, -3);
//针对当前时间,提供了简化的偏移方法(例如昨天、上周、上个月等):
//昨天
DateUtil.yesterday()
//明天
DateUtil.tomorrow()
//上周
DateUtil.lastWeek()
//下周
DateUtil.nextWeek()
//上个月
DateUtil.lastMonth()
//下个月
DateUtil.nextMonth()
7)日期时间差
Date date1 = DateUtil.parse("2019-09-20 17:35:35");
Date date2 = DateUtil.parse("2019-09-17 14:35:35");
//这里若date1和date2换位置,输出结果不变:betweenDay = 3
long betweenDay = DateUtil.between(date1, date2, DateUnit.DAY);
8)其它
//年龄:ageOfNow = 28
int ageOfNow = DateUtil.ageOfNow("1991-01-13");
//是否闰年:leapYear = false
boolean leapYear = DateUtil.isLeapYear(2019);