java时间搓转为日期

    public static void main(String[] args) {
        // 创建当前日期对象
        Date now = new Date();
        
        // 获取当前时间毫秒值,作为结束时间
        Long endTime = now.getTime();
        
        // 获取当前时间的Calendar实例
        Calendar cd = Calendar.getInstance();
        cd.setTime(now);
        
        // 回溯15分钟,设置为开始时间
        cd.add(Calendar.MINUTE, -15);
        
        // 获取回溯15分钟后的时间毫秒值,作为开始时间
        Long startTime = cd.getTime().getTime();
        
        // 获取回溯15分钟后的日期对象
        Date time = cd.getTime();
        System.out.println("time:"+time);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(time);
        System.out.println("format1:"+format1);

        // 将给定的时间转换为本地日期时间,以便在当前时区内更好地处理和显示
        LocalDateTime localDateTime = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        
        // 将给定的时间转换为Instant类型,用于后续可能的时间计算或比较
        Instant instant1 = time.toInstant();


        Instant instant = Instant.ofEpochSecond(startTime);

        // 将 Instant 转换为 LocalDateTime 对象
        LocalDateTime dateTime = LocalDateTime.ofInstant(instant1, ZoneId.systemDefault());
        System.out.println("dateTime"+dateTime);
        // 打印结果
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = localDateTime.format(formatter);
        System.out.println("LocalDateTime: " + formattedDateTime);
    }

 

posted @ 2024-09-18 09:56  凉忆~  阅读(43)  评论(0)    收藏  举报