JAVA获取当前时间并且指定格式,直接修改时间

SimpleDateFormat类概述

SimpleDateFormat可以对Date对象,进行格式化和解析。
格式化

package com.shengda.Demo11Date;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo3 {
    public static void main(String[] args) {
        // 当前时间的Date对象
        Date date = new Date();

        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String result1 = sdf.format(date);
        System.out.println(result1);
    }
}

解析

package com.shengda.Demo11Date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo4 {
    public static void main(String[] args) throws ParseException {
        String s = "2048-01-01";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date date = sdf.parse(s);
        System.out.println(date);
    }
}

JDK8版本之后的对日期添加修改的操作

package com.shengda.Demo11Date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateDemo5 {
    public static void main(String[] args) throws ParseException {
        JDKMethod(); // 8版本之后

        // JDK8版本之后
        String s = "2020年11月11日 00:00:00";

        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(s, pattern);
        LocalDateTime newLocalDateTime = localDateTime.minusDays(1);  // 减少一天
        // LocalDateTime newLocalDateTime = localDateTime.plusDays(1);  // 表示增加一天
        String result = newLocalDateTime.format(pattern);
        System.out.println(result);

    }

    private static void JDKMethod() throws ParseException {
        String s = "2020年11月11日 00:00:00";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date date = sdf.parse(s);
        long time = date.getTime();
        time = time+(1000*60*60*24);
        Date newDate = new Date(time);
        String result = sdf.format(newDate);
        System.out.println(result);
    }
}

将时间修改到指定的日期

package com.shengda.Demo12DateJDK8;

import java.time.LocalDateTime;

public class JDK8DateDemo6 {
    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.of(2020, 12, 12, 12, 12, 12);
        // LocalDateTime newLocalDateTime = localDateTime.withYear(2044);  // 修改到指定的年份
        LocalDateTime newLocalDateTime = localDateTime.withMonth(11);  // 修改到指定的月份
        System.out.println(newLocalDateTime);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值