I'm having trouble converting a UTC date string to local date string in Android. Example in case is,
I've input UTC date string as 2018-02-28T02:42:41Z
I'm in PST timezone but when I tried to convert to local timezone it doesn't change. I get February 28, 2018 02:42 AM
which is incorrect.
public static String convertUTCtoLocalTime(String utcDateString) throws Exception{
SimpleDateFormat dateFormatter;
//create a new Date object using the UTC timezone
Log.v(TAG, "Input utc date:" + utcDateString);
dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcDate = dateFormatter.parse(utcDateString);
//Convert the UTC date to Local timezone
dateFormatter = new SimpleDateFormat("MMMM dd, yyyy hh:mm a");
dateFormatter.setTimeZone(TimeZone.getDefault());
String formattedDate = dateFormatter.format(utcDate);
Log.v(TAG, "convertUTCtoLocalTime: local time:" + formattedDate);
return lv_dateFormateInLocalTimeZone;
}
I don't fully understand the difference but similar conversion works in "swift" as shown below,
static func utcDateToLocal(utcdate: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" //Input Format 2018-02-28T02:42:41Z
dateFormatter.timeZone = NSTimeZone(name: "UTC")! as TimeZone
let UTCDate = dateFormatter.date(from: utcdate)
dateFormatter.dateFormat = "MMMM dd, yyyy hh:mm a" // Output Format
dateFormatter.timeZone = TimeZone.current
let UTCToCurrentFormat = dateFormatter.string(from: UTCDate!)
return UTCToCurrentFormat
}
Swift example gives me out "February 27, 2018 06:42 PM" which is the correct one.
Swift is using v3.x and
Android is, Studio 3.1.1 Build #AI-173.4697961, built on April 3, 2018 JRE: 1.8.0_152-release-1024-b01 x86_64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Mac OS X 10.13.4
I'm running both examples on the same machine. Any hints to solve issue on Android would be really useful.