Java 8 时间,字符串和Long时间戳互转

每次用到时间相关的处理都下意识的想到了一个很讨人厌但是读起来又及其顺口的类:SimpleDateFormat,有木有同感!
不过java8来以后就基本告别自行车,不SimpleDateFormat 了。
下面就简单的总结一下java 8中常见的日期、时间的使用。只写最常用的几个点,这里面的方法太多了。
1、取当前时间戳

Long millisecond = Instant.now().toEpochMilli();  // 精确到毫秒
Long second = Instant.now().getEpochSecond();// 精确到秒

2、将Long类型的时间戳转成字符串(这个页面要展示字符串的时候就很有用)

    /**
     * 将Long类型的时间戳转换成String 类型的时间格式,时间格式为:yyyy-MM-dd HH:mm:ss
     */
    public static String convertTimeToString(Long time){
        Assert.notNull(time, "time is null");
        DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time),ZoneId.systemDefault()));
    }

3、与2相反,将字符串时间转成Long类型的时间戳(前端给后端传字符串类型的时间时,这个很有用)

    /**
     * 将字符串转日期成Long类型的时间戳,格式为:yyyy-MM-dd HH:mm:ss
     */
    public static Long convertTimeToLong(String time) { 
        Assert.notNull(time, "time is null");
        DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parse = LocalDateTime.parse("2018-05-29 13:52:50", ftf);
        return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }  

4、我的日期时间工具类中的其他方法也贴上来,有用没用随缘

    /**
     * 取本月第一天
     */
    public static LocalDate firstDayOfThisMonth() {
        LocalDate today = LocalDate.now();
        return today.with(TemporalAdjusters.firstDayOfMonth());
    }

    /**
     * 取本月第N天
     */
    public static LocalDate dayOfThisMonth(int n) {
        LocalDate today = LocalDate.now();
        return today.withDayOfMonth(n);
    }

    /**
     * 取本月最后一天
     */
    public static LocalDate lastDayOfThisMonth() {
        LocalDate today = LocalDate.now();
        return today.with(TemporalAdjusters.lastDayOfMonth());
    }

    /**
     * 取本月第一天的开始时间
     */
    public static LocalDateTime startOfThisMonth() {
        return LocalDateTime.of(firstDayOfThisMonth(), LocalTime.MIN);
    }


    /**
     * 取本月最后一天的结束时间
     */
    public static LocalDateTime endOfThisMonth() {
        return LocalDateTime.of(lastDayOfThisMonth(), LocalTime.MAX);
    }

总结&说明:
1、第2条和第3条中的Assert.notNull(time, "time is null"); 是spring框架的util方法,用其他方法判空也是一样,不过我觉得spring的这个写法比较好,大家可以参考他的思路或者说做法。
2、建议大家一定要将日期时间相关处理方法集中起来,放到一个DateAndTimeUtils之类的工具类中统一使用和管理。这样做第一避免重复造轮子,第二避免同一量车造出来各式各样的轮子。(想象一下SimpleDateFormat和DateTimeFormatter搅和在一起是什么样的一种酸爽0.0)

  • 9
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值