其它时区的0时0分0秒的时间戳

本文详细介绍了如何在Java中获取当前时区的0时0分0秒时间戳,以及如何获取指定时区的时分秒时间戳。通过Calendar、SimpleDateFormat和TimeZone的结合使用,实现了跨时区时间的准确获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获取当前时区的0时0分0秒时间戳很容易:

long current = System.currentTimeMillis();
long zero = current/(1000*3600*24)*(1000*3600*24) - TimeZone.getDefault().getRawOffset();

但是要获取指定时区的时分秒就比较麻烦了

1.获取指定时区的当前时间的时间戳, 你可能会想到用Calendar

private static Long getZeroDate() {
    TimeZone timeZone = TimeZone.getTimeZone("GMT-5:00");//指定别的时区
    Calendar calendar = Calendar.getInstance(timeZone);
    return calendar.getTime().getTime();
}

但是无论你指定的时区是什么"GMT-5:00"/"GMT-9:00" ... 都会是系统默认时区的时间戳, 所以需要通过SimpleDateFormat

public static String getOtherTimeZoneTime() {
    TimeZone timeZone = TimeZone.getTimeZone("GMT-5:00");
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd EEEE HH:mm:ss");
    System.out.println("timezone: " + timeZone.toString());
    simpleDateFormat.setTimeZone(timeZone);
    return simpleDateFormat.format(new Date());  // 返回的是格式化的字符串
}

先获取时间字符串, 然后在获取时间戳, 注意不能使用同一个SimpleDateFormat, 因为第一个设置了时区, 第二个不能设置时区, 否则会出错

private static Long getTimeNum(){
    String centralTime = getOtherTimeZoneTime();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd EEEE HH:mm:ss");
    Date date = null;
    try {
        date = simpleDateFormat.parse(centralTime);    // 直接转换为时间
    } catch (ParseException e) {
        e.printStackTrace();
    }
    if(date != null){
        return date.getTime();    // 获取时间戳
    }
    return null;
}

2.获取指定时区的0时0分0秒时间戳

// 获取指定时区今天零点零分零秒的毫秒数	
// 小于8点用-16
long zero=currentTime/(1000*3600*24)*(1000*3600*24)-TimeZone.getTimeZone("GMT-16:00").getRawOffset();
// 大于8点用+8
long zero=currentTime/(1000*3600*24)*(1000*3600*24)-TimeZone.getTimeZone("GMT+8:00").getRawOffset();

为什么是GMT-16:00 ?, GMT+8 ?   经过测试得到的, 我也不知道为啥

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值