【时间戳常用的几个方法】


前言

最近一直在用时间戳,记录下相关方法;


一、字符串转时间戳

    /**
     * 西五区 短时间转为Date
     * @param dateStr 2022-02-16
     * @return Long
     */
    public static Long parseShortStringDateWestFive(String dateStr){
        try {
            SimpleDateFormat dateFormatShort = new SimpleDateFormat("yyyy-MM-dd");
            dateFormatShort.setTimeZone(TimeZone.getTimeZone("GMT-5:00"));
            return dateFormatShort.parse(dateStr).getTime();
        } catch (ParseException e) {
            LOGGER.error("parseShortStringDateWestFive is fail", e);
        }
        return null;
    }

二、获取某个时区零点时间戳

代码如下(示例):

/**
     * 根据时区获取当前月初零点时间戳
     * @param timeZone
     * @return
     */
    public static long getMonthZeroTimeStamp(String timeZone){
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
        // 日
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        // 时
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        // 分
        calendar.set(Calendar.MINUTE, 0);
        // 秒
        calendar.set(Calendar.SECOND, 0);
        // 毫秒
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }
    // 调用
    getMonthZeroTimeStamp("GMT-5:00");

三、 时间戳相差几天

代码如下(示例):

// 获取西五区 时间
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    sdf.setTimeZone(TimeZone.getTimeZone("GMT-5:00"));
                    Date date = new Date();
                    String stringDate = sdf.format(date);
                    Date cur = sdf.parse(stringDate);
                    day = (cur.getTime() - orderEntity.getAddTime()) / (24 * 60 * 60 * 1000);

---

# 总结
以上就是今天要讲的内容,本文仅仅简单记录了时间戳的几个相关常用的方法。
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值