Last active
August 29, 2015 14:10
-
-
Save damianpetla/86ba0b2a6fabdbf9cb38 to your computer and use it in GitHub Desktop.
Simple way to convert ISO8601 date/time to localised date/time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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