LocalDateTime类型相关操作
.
-
LocalDateTime 与 String 的相互转换
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime time = LocalDateTime.now(); String localTime = df.format(time); System.out.println("LocalDateTime转成String类型的时间:"+localTime); LocalDateTime ldt = LocalDateTime.parse("2018-01-12 17:07:05",df); System.out.println("String类型的时间转成LocalDateTime:"+ldt);
-
比较
//获取当前时间 LocalDateTime nowTime= LocalDateTime.now(); //自定义时间 LocalDateTime endTime = LocalDateTime.of(2017, 10, 22, 10, 10, 10); //比较 现在的时间 比 设定的时间 之前 返回的类型是Boolean类型 true System.out.println(nowTime.isAfter(endTime)); //比较 现在的时间 比 设定的时间 之后 返回的类型是Boolean类型 false System.out.println(nowTime.isBefore(endTime)); //比较 现在的时间 和 设定的时候 相等 返回类型是Boolean类型 false System.out.println(nowTime.equals(endTime));
-
获取年月日时分秒
LocalDateTime newLDT = LocalDateTime.now(); int year = newLDT.getYear();//年 int month = newLDT.getMonth().getValue();//月 int dayOfMonth = newLDT.getDayOfMonth();//日 int hour = newLDT.getHour();//时 int minute = newLDT.getMinute();//分 int second = newLDT.getSecond();//秒
-
相差天数和月份
public class Demo { public static void main(String[] args) throws ParseException { LocalDateTime of1 = LocalDateTime.of(2019, 9, 25, 1, 1);//2018-9-25 01:01 LocalDateTime of2 = LocalDateTime.of(2020, 9, 25, 23, 16); //2019-9-25 23:16 System.out.println(monthDiff(of1,of2));//相差月份 12 System.out.println(dateDiff(of1,of2));//相差天数 365 } /** * 计算两个时间点的天数差 * @param dt1 第一个时间点 * @param dt2 第二个时间点 * @return int,即要计算的天数差 */ public static int dateDiff(LocalDateTime dt1,LocalDateTime dt2){ //获取第一个时间点的时间戳对应的秒数 long t1 = dt1.toEpochSecond(ZoneOffset.ofHours(0)); //获取第一个时间点在是1970年1月1日后的第几天 long day1 = t1 /(60*60*24); //获取第二个时间点的时间戳对应的秒数 long t2 = dt2.toEpochSecond(ZoneOffset.ofHours(0)); //获取第二个时间点在是1970年1月1日后的第几天 long day2 = t2/(60*60*24); //返回两个时间点的天数差 return (int)(day2 - day1); } /** * 获取两个时间点的月份差 * @param dt1 第一个时间点 * @param dt2 第二个时间点 * @return int,即需求的月数差 */ public static int monthDiff(LocalDateTime dt1,LocalDateTime dt2){ //获取第一个时间点的月份 int month1 = dt1.getMonthValue(); //获取第一个时间点的年份 int year1 = dt1.getYear(); //获取第二个时间点的月份 int month2 = dt2.getMonthValue(); //获取第二个时间点的年份 int year2 = dt2.getYear(); //返回两个时间点的月数差 return (year2 - year1) *12 + (month2 - month1); } }