Conversion of UTC to IST time in java is working in LOCAL but not in CLOUD SERVER

只谈情不闲聊 提交于 2019-12-10 14:24:21

问题


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.

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;
}

回答1:


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.

So, the entire concept of converting utcDate to ISTDate is flawed.
(BTW: Bad name. Java conventions says it should be istDate)

Now, if you want the code to return the date as text in IST time zone, then you need to request that:

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);



回答2:


Using Java 8 New 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);


来源:https://stackoverflow.com/questions/35127299/conversion-of-utc-to-ist-time-in-java-is-working-in-local-but-not-in-cloud-serve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!