获取当前时区的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 ? 经过测试得到的, 我也不知道为啥