发布于2022-09-30 20:03 阅读(422) 评论(0) 点赞(5) 收藏(0)
I need to get the today midnight time as milliseconds. For example, today's date is 2020-03-20 and I convert this today midnight as milliseconds using the below code. If it works fine in my local environment, but the problem is when I deploy this code to the server, the server has UTC time zone, So even I pass the timezone, the milliseconds returned is wrong. After debugging I found out that this is happening due to parsing the Date, the date uses the default timeZone. I tried to set the timeZone in the Date, but the millisecond value returning is wrong even the date is 2020/03/20 00:00:00. For you to understand more below are some cases.
In the local Environment: Time Zone pass to method = "Asia/Colombo"
Date in milliseconds = 1584642600000
Converted date = Fri Mar 20 2020 00:00:00
In the Server Environment: Time Zone pass to method = "Asia/Colombo"
Date in milliseconds = 1584662400000
Converted date = Fri Mar 20 2020 05:30:00
Note that here Time Zone is the value I pass to my method parameter. I'm using java 8.
private static final String DATE_FORMAT = "yyyy/MM/dd 00:00:00";
private long getTMT(String timeZone) {
try {
ZoneId zoneId = ZoneId.of(timeZone);
ZonedDateTime currentZone = ZonedDateTime.now(zoneId);
ZonedDateTime zonedDateTime =
currentZone.withZoneSameInstant(zoneId);
DateTimeFormatter format =
DateTimeFormatter.ofPattern(DATE_FORMAT);
String formattedDateTime = zonedDateTime.format(format);
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Date date = sdf.parse(formattedDateTime);
return date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
}
Hope I explained my question clearly, please let me know your answers/comments on this.
Thank you.
Formatting to string and then parsing from it is a horrible solution, especially since you also have to also construct all these parsers every time, and your format effectively has hacks in it.
There are simpler ways to both construct a midnight ZDT:
ZonedDateTime zdt = LocalDate.now(zoneId).atTime(LocalTime.MIDNIGHT).atZone(zoneID);
And then extracting the epoch-millis value from it:
long epoch = zdt.toInstant().toEpochMilli();
Alternatively, since you know that milliseconds and nanoseconds are always 0
at midnight, this is marginally faster:
long epoch = zdt.toEpochSecond() * 1000;
The second approach wouldn't work if your time is arbitrary, as it will always ignore milli-of-second
value.
作者:黑洞官方问答小能手
链接:http://www.javaheidong.com/blog/article/526537/7c60824e4a4a76a833e1/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!