Android Studio 4.0, Java 6. My GMT is GMT + 03:00
defaultConfig {
minSdkVersion 17
targetSdkVersion 28
const val LONDON_TIME_ZONE_ID = "Europe/London"
const val DEFAULT_DATE_JSON_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.000'Z'"
fun fromDateToLondonDate(localDate : Date) : Date? {
val dateLondonAsString = fromDate2LondonDateAsString(localDate)
val timeZoneLondon : TimeZone = TimeZone.getTimeZone(LONDON_TIME_ZONE_ID)
val dateLondon = getDateFromString(dateLondonAsString, timeZoneLondon)
if (BuildConfig.DEBUG)
Log.d("", "fromDateToLondonDate:" +
"\nlocalDate = $localDate"+
"\ndateLondonAsString = $dateLondonAsString"+
"\ndateLondon = $dateLondon")
return dateLondon
}
fun fromDate2LondonDateAsString(date : Date) : String? {
val timeZoneLondon : TimeZone = TimeZone.getTimeZone(LONDON_TIME_ZONE_ID)
val formatter: DateFormat = SimpleDateFormat(DEFAULT_DATE_JSON_FORMAT)
formatter.setTimeZone(timeZoneLondon)
val dateAsString : String = formatter.format(date)
return dateAsString
}
fun getDateFromString(str: String?, tz: TimeZone?): Date? {
return try {
val sdf = SimpleDateFormat(DEFAULT_DATE_JSON_FORMAT);
sdf.setTimeZone(tz)
val date = sdf.parse(str)
return date
} catch (e: ParseException) {
//e.printStackTrace();
null
}
}
and here result:
fromDateToLondonDate:
localDate = Tue Jun 16 13:14:59 GMT+03:00 2020
dateLondonAsString = 2020-06-16T11:14:59.000Z
dateLondon = Tue Jun 16 13:14:59 GMT+03:00 2020
as you can see the local date is Tue Jun 16 13:14:59 GMT+03:00 2020 and success convert to London date as String -> dateLondonAsString = 2020-06-16T11:14:59.000Z
Nice. But I need to convert String to London Date. And I use method getDateFromString and result is not correct:
dateLondon = Tue Jun 16 13:14:59 GMT+03:00 2020
The correct London Date must be : Tue Jun 16 11:14:59 GMT+03:00 2020
Why getDateFromString
not correct convert from string to date?