Skip to content

Instantly share code, notes, and snippets.

@damianpetla
Last active August 29, 2015 14:10
Show Gist options
  • Save damianpetla/86ba0b2a6fabdbf9cb38 to your computer and use it in GitHub Desktop.
Save damianpetla/86ba0b2a6fabdbf9cb38 to your computer and use it in GitHub Desktop.
Simple way to convert ISO8601 date/time to localised date/time
import java.util.TimeZone
import android.text.format.Time
import java.text.SimpleDateFormat
import java.text.DateFormat
/**
* Created by loop on 24/11/14.
*/
/**
* This is a singleton.
*/
object DateUtil {
val utcDateParser = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").setUTCTimeZone()
val dateShortFormatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
private fun SimpleDateFormat.setUTCTimeZone(): SimpleDateFormat {
this.setTimeZone(TimeZone.getTimeZone(Time.TIMEZONE_UTC))
return this
}
}
/**
* Converts ISO 8601 date/time to localized formatted date/time
*/
fun String.pretty(): String {
val parsed = DateUtil.utcDateParser.parse(this)
val formatted = DateUtil.dateShortFormatter.format(parsed)
return formatted
}
SmallTest
public fun testStringToFormattedDate() {
val testDate = "2014-11-03T15:03:11.000Z"
val formattedDate = testDate.pretty()
assertEquals("11/3/14 3:03 PM", formattedDate)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment