java中给当前日期加减年月日(保留时分秒)

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;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值