日期格式LocalDateTime

日期格式LocalDateTime
最近做项目时频繁使用对时间进行操作,用的特别不舒服。就发现了我们的主角。自 Java8开始, JDK中其实就增加了一系列表示日期和时间的新类,最典型的就是 LocalDateTime。他的功能完爆老版的Date。

一、获取当前此刻的时间

public class text {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();

        System.out.println("当前时刻:"+ now);
        System.out.println("当前年份:"+ now.getYear());
        System.out.println("当前月份:"+ now.getMonth());
        System.out.println("当前日份:"+ now.getDayOfMonth());
        System.out.println("当前周数:"+ now.getDayOfWeek());
        System.out.println("当前时:"+ now.getHour());
        System.out.println("当前分:"+ now.getMinute());
        System.out.println("当前秒:"+ now.getSecond());
    }
}

结果

二、构造一个指定年、月、日的时间:

时间:2020-01-07T14:53:32

LocalDateTime date = LocalDateTime.of(2020, Month.JANUARY, 7, 14, 53, 32);

三、修改日期

public class text {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println("时间"+ now);
        now = now.minusYears(1);// 减少 1 年
        System.out.println("时间"+ now);
        now = now.plusMonths(1);// 增加 1 个月
        System.out.println("时间"+ now);
        now = now.withYear(2021);// 直接修改年份到2021年
        System.out.println("时间"+ now);
        now = now.withHour(13);//改到中午一点
        System.out.println("时间"+ now);
    }
}

在这里插入图片描述

四、格式化日期

public class text {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();

        String result1 = now.format(DateTimeFormatter.ISO_DATE);
        String result2 = now.format(DateTimeFormatter.BASIC_ISO_DATE);
        String result3 = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

        System.out.println("(样式一):" + result1);
        System.out.println("(样式二):" + result2);
        System.out.println("(样式三):" + result3);
    }
}

在这里插入图片描述

五、时间反解析

public class text {
    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.parse("2020---01--07 15:11", DateTimeFormatter.ofPattern("yyyy---MM--dd HH:mm"));
        System.out.println("字符串反解析后的时间为:" + time);
    }
}

在这里插入图片描述

线程安全问题

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值