我正在使用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;
}
答案 0 :(得分:4)
Java Date
对象已经/始终为UTC。时区是格式化为文本时应用的内容。 Date
不能(不应该!)在UTC以外的任何时区。
因此,将utcDate
转换为ISTDate
的整个概念存在缺陷
(顺便说一句:糟糕的名字.Java惯例说它应该是istDate
)
现在,如果您希望代码在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);
答案 1 :(得分:1)
使用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);