I am trying to convert current UTC time (time from my Linux server) using below code.
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class UtcToIst {
public static void main(String[] args) {
List<String> timeZones = new ArrayList<String>();
String ISTDateString = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = sdf.format(new Date());
System.err.println("utcTime: " + utcTime);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String pattern = "dd-MM-yyyy HH:mm:ss";
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern);
try {
String formattedDate = formatter.format(utcTime);
Date ISTDate = sdf.parse(formattedDate);
ISTDateString = formatter.format(ISTDate);
timeZones.add(utcTime+ ","+ ISTDateString);
} catch(Exception e) {
e.printStackTrace();
}
for(String i: timeZones) {
System.out.println(i);
}
}
}
When I execute the code, I get the below exception:
utcTime: 05-11-2018 12:55:28
java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(DateFormat.java:310)
at java.text.Format.format(Format.java:157)
at UtcToIst.main(UtcToIst.java:21)
I see that the UTC time being fetched correctly as: 05-11-2018 12:55:28 But the code is unable to parse the string into IST(Indian Standard Time). I am unable understand how can I fix the problem. Could anyone let me know what is the mistake I am making here and how can I sort it out ?