java java中UTC到IST时间的转换在LOCAL中有效,但在CLOUD SERVER中无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35127299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conversion of UTC to IST time in java is working in LOCAL but not in CLOUD SERVER
提问by Vicky
I am working in date conversion in java in that i am using following code snippet to convert the UTC time to IST format.It is working properly in the local when i run it but when i deploy it in server its not converting , its displaying only the utc time itself.Is there any configuaration is needed in server side.Please help me out.
我正在 Java 中进行日期转换,因为我正在使用以下代码片段将 UTC 时间转换为 IST 格式。当我运行它时它在本地正常工作,但是当我将它部署到服务器中时它没有转换,它只显示UTC 时间本身。服务器端是否需要任何配置。请帮帮我。
CODE SNIPPET:
代码片段:
DateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String pattern = "dd-MM-yyyy HH:mm:ss";
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern);
try {
String formattedDate = formatter.format(utcDate);
Date ISTDate = sdf.parse(formattedDate);
String ISTDateString = formatter.format(ISTDate);
return ISTDateString;
}
采纳答案by Andreas
Java Date
objects are already/always in UTC. Time Zone is something that is applied when formatting to text. A Date
cannot (should not!) be in any time zone other than UTC.
JavaDate
对象已经/总是在 UTC 中。时区是在格式化文本时应用的东西。ADate
不能(不应该!)位于 UTC 以外的任何时区。
So, the entire concept of converting utcDate
to ISTDate
is flawed.
(BTW: Bad name. Java conventions says it should be istDate
)
因此,转换utcDate
为的整个概念ISTDate
是有缺陷的。
(顺便说一句:名字不好。Java 约定说它应该是istDate
)
Now, if you want the code to return the date as text in IST time zone, then you need to request that:
现在,如果您希望代码将日期作为 IST 时区中的文本返回,那么您需要请求:
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata")); // Or whatever IST is supposed to be
return formatter.format(utcDate);
回答by Rakesh Chaudhari
Using Java 8 New API,
使用 Java 8 新 API,
Instant s = Instant.parse("2019-09-28T18:12:17Z");
ZoneId.of("Asia/Kolkata");
LocalDateTime l = LocalDateTime.ofInstant(s, ZoneId.of("Asia/Kolkata"));
System.out.println(l);