Skip to content

Instantly share code, notes, and snippets.

@henriquehorbovyi
Last active November 5, 2021 13:16
Show Gist options
  • Save henriquehorbovyi/04bccb2e11a203eede508fb441eb242d to your computer and use it in GitHub Desktop.
Save henriquehorbovyi/04bccb2e11a203eede508fb441eb242d to your computer and use it in GitHub Desktop.
const val ISO6801 = "yyyy-MM-dd\'T\'HH:mm:ss\'Z\'"
const val HUMAN_FORMAT = "dd/MM/yyyy \'at\' HH:mm"
/*
* Sample:
* "2021-10-24T14:32:12Z".formatAsDate(ISO6801, HUMAN_FORMAT)
* */
fun String.formatAsDate(patternInput: String, patternOutput: String): String {
val dateInput = SimpleDateFormat(patternInput, Locale("en"))
val dateOutput = SimpleDateFormat(patternOutput, Locale("en"))
return try {
val date = dateInput.parse(this) ?: Date()
dateOutput.format(date)
} catch (e: ParseException) {
e.printStackTrace()
"-"
}
}
/*
* Sample:
* val now = Date().now()
* */
fun Date.now(pattern: String = "yyyy-MM-dd\'T\'HH:mm:ss.SSS"): String {
val formatter = SimpleDateFormat(pattern, Locale.ENGLISH)
return formatter.format(this)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment