JDK8版本
LocalDate是不可变的和线程安全的,没有带时分秒的,如果处理带时分秒的时间可以用LocalDateTime这个类。
LocalDate
//获取当前日期
LocalDate now = LocalDate.now();
//获取昨天的日期
LocalDate yesterday = now.plusDays(-1);
//根据年月日获取日期
LocalDate setDate = LocalDate.of(2019, 07, 10);
//字符串转日期
LocalDate parse = LocalDate.parse("2019-07-14");
//将指定日期格式化,也就是将日期转换为字符串
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String todayStr = dateTimeFormatter.format(yesterday);
//获取下一年的今天,参数是日期相加多少年
LocalDate localDate = now.plusYears(1);
//获取日期的年
int year = localDate.getYear();
//获取日期的月
Month month = localDate.getMonth();
//获取日期的天,这个是获取这个月的天数
int dayOfMonth = localDate.getDayOfMonth();
//获取当前日期的天数,也就是今年一共过了多少天,2019-07-14返回197
int dayOfYear = localDate.getDayOfYear();
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
输出结果:
LocalDateTime
//获取当前日期
LocalDateTime now = LocalDateTime.now();
//格式化时间类
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//讲字符串转化为时间,带格式
LocalDateTime ldp = LocalDateTime.parse("2019-07-17 13:46:24",dtf);
//获取日期中的小时
int hour = ldp .getHour(); //这个返回的是13
//替换时间中的小时
ldp.withHour(23); //这个返回的是2019-07-17T23:46:24
//计算两个时间差,第二个时间减去第一个时间
Duration duration = Duration.between(ldt, ldp);
//两个日期相差多少个小时
long hour = duration.toHours();
//两个日期相差多少毫秒
long millis = duration.toMillis();
//两个日期相差多少分钟
long minute = duration.toMinutes();
//两个日期相差多少天
long day = duration.toDays();
SimpleDateFormat 是 Java 中一个非常常用的类用来对日期字符串进行解析和格式化输出,但如果使用不小心会导致非常微妙和难以调试的问题,因为 DateFormat 和 SimpleDateFormat 类不都是线程安全的,在多线程环境下调用 format() 和 parse() 方法应该使用同步代码来避免问题。
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date invalidtimeDate = null;
String invalidTime = "";
//获取开始时间的下一年时间
try {
//将字符串转化为日期
invalidtimeDate = simpleDateFormat.parse("2019-06-26");
Calendar calendar = new GregorianCalendar();
//设置指定日期
calendar.setTime(invalidtimeDate);
//设置当前日期的下一年
calendar.add(Calendar.YEAR, 1);
//获取下一年的日期并格式化输出
invalidTime = simpleDateFormat.format(calendar.getTime());
} catch (ParseException e) {
e.printStackTrace();
}