Conversion of UTC to IST time in java is working i

2019-06-23 09:07发布

问题:

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