package com.test;
import java.math.BigDecimal;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class hello {
public static void main(String[] args) throws ParseException {
String aaaa = dateHandler(new Date(),12L);
System.out.println("十二个月之前的日期为: " + aaaa);
String s = "2023-01-11 11:11:11";
System.out.println(toLocalDateTime(new Date()));
System.out.println(s.substring(s.lastIndexOf(" ")).trim());
LocalDateTime time = toLocalDateTime(new Date());
System.out.println(toDate( time.plusMonths(1)));
System.out.println(new Date());
}
//todo 转换方法开始
public static LocalDateTime toLocalDateTime(Date date) {
return date == null ? null : date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
public static Date toDate(LocalDateTime localDateTime) {
LocalTime localTime = localDateTime.atZone(ZoneId.systemDefault()).toLocalDateTime().toLocalTime();
LocalDate localDate = localDateTime.atZone(ZoneId.systemDefault()).toLocalDateTime().toLocalDate();
return localTime == null ? null : Date.from(LocalDateTime.of(localDate, localTime).atZone(ZoneId.systemDefault()).toInstant());
}
//todo 转换方法结束
//参考加减的方法
/* if (null != dto2.getLastVerificationDate()) {
update.setVerificationExpDate(MtDateTimeHelper
.toDate(MtDateTimeHelper.toLocalDateTime(dto2.getLastVerificationDate())
.plusMonths(MtFieldsHelper.getOrEmptyLong(dto2.getVerificationPeriod()))
.minusDays(1L)));
}*/
public static String dateHandler(Date date,Long day) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format1 = format.format(date);
//将时间转为LocalDate格式
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDate localDate = LocalDate.parse(format1, dateTimeFormatter);
//获取十二个月之前的时间
LocalDate localDate12MonthsBefore = localDate.plusMonths(day);
LocalDate localDate1 = localDate12MonthsBefore.minusDays(1);
//将时间转为字符串
String toString = localDate1.toString();
return toString;
}
}
java中给当前日期加减年月日(保留时分秒)
最新推荐文章于 2024-10-16 10:13:45 发布