Check DateFormat
and SimpleDateFormat
classes from Java Docs
https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
fun getTimeMillisFromString(dateValue: String, dateFormat: String): Long {
val sdf = SimpleDateFormat(dateFormat)
try {
return sdf.parse(dateValue).time
} catch (e: ParseException) {
e.printStackTrace()
}
}
return 0L
This function will return the long format of the time. You need to pass the string you received and the format in which the string is. For example, getTimeMillisFromString("Sun Jul 25 00:00:00 GMT+09:00 2021", "yyyy.MM.dd HH:mm:ss z")
You may have to set timezone as GMT like sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
After you have the long format date, you can convert it into any string format you want using SimpleDateFormat
. For example,
SimpleDateFormat(DATE_FORMAT_HYPHEN_DD_MM_YY, Locale.getDefault()).format(calender.time)
This should give you the expected string.
Check this answer also SimpleDateFormat parse loses timezone
And this one also for more info Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST