I am downloading some JSON data from a webservice. In this JSON I\'ve got some Date/Time values. Everything in UTC. How can I parse this date string so the result Date objec
If you had a timestamp (Long) as input instead (for the UTC time), since this is on Android, you can do something as such:
fun DateFormat.formatUtcEpochSecond(epochSecond: Long): String = format(CalendarEx.getFromEpochSecond(epochSecond).time)
fun DateFormat.formatUtcEpochMs(epochMilli: Long): String = format(CalendarEx.getFromEpochMilli(epochMilli).time)
CalendarEx.kt
object CalendarEx {
@JvmStatic
fun getFromEpochMilli(epochMilli: Long): Calendar {
val cal = Calendar.getInstance()
cal.timeInMillis = epochMilli
return cal
}
@JvmStatic
fun getFromEpochSecond(epochSecond: Long): Calendar {
val cal = Calendar.getInstance()
cal.timeInMillis = epochSecond * 1000L
return cal
}
}
DateHelper.kt
/**
* gets the default date formatter of the device
*/
@JvmStatic
fun getFormatDateUsingDeviceSettings(context: Context): java.text.DateFormat {
return DateFormat.getDateFormat(context) ?: SimpleDateFormat("yyyy/MM/dd", Locale.getDefault())
}
/**
* gets the default time formatter of the device
*/
@JvmStatic
fun getFormatTimeUsingDeviceSettings(context: Context): java.text.DateFormat {
return DateFormat.getTimeFormat(context) ?: SimpleDateFormat("HH:mm", Locale.getDefault())
}
Example usage:
val dateFormat = DateHelper.getFormatDateUsingDeviceSettings(this)
val timeFormat = DateHelper.getFormatTimeUsingDeviceSettings(this)
val timeStampSecondsInUtc = 1516797000L
val localDateTime = Instant.ofEpochSecond(timeStampSecondsInUtc).atZone(ZoneId.ofOffset("UTC", ZoneOffset.ofHours(0))).toLocalDateTime()
Log.d("AppLog", "input time in UTC:" + localDateTime)
Log.d("AppLog", "formatted date and time in current config:${dateFormat.formatUtcEpochSecond(timeStampSecondsInUtc)} ${timeFormat.formatUtcEpochSecond(timeStampSecondsInUtc)}")