Skip to content

Instantly share code, notes, and snippets.

@nadar71
Created October 21, 2020 09:49
Show Gist options
  • Save nadar71/0d84e727d3c55175a9048d5023f819a8 to your computer and use it in GitHub Desktop.
Save nadar71/0d84e727d3c55175a9048d5023f819a8 to your computer and use it in GitHub Desktop.
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
// Converting from String to Date
fun String.getDateWithServerTimeStamp(): Date? {
val dateFormat = SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
Locale.ENGLISH)
// 21/08/2020 commented due to something changed on cloud during the morning of this day not revealed
// dateFormat.timeZone = TimeZone.getTimeZone("UTC")
try {
return dateFormat.parse(this)
} catch (e: ParseException) {
return null
}
}
// Getting hours and minute from string server timestamp in format HH:mm
fun String.getHHmmFromDate(): String{
val cal = Calendar.getInstance()
cal.time = this.getDateWithServerTimeStamp()!!
val hours = cal.get(Calendar.HOUR_OF_DAY)
val minutes = cal.get(Calendar.MINUTE)
return "${hours}:${minutes}"
}
// Getting DD-MM-YYYY string server timestamp from Date
fun String.getDDMMYYYYFromDate(): String{
val cal = Calendar.getInstance()
cal.time = this.getDateWithServerTimeStamp()!!
val day = cal.get(Calendar.DAY_OF_MONTH)
var month = (cal.get(Calendar.MONTH)+1).toString()
if (month.length <= 1) month = "0$month"
val year = cal.get(Calendar.YEAR)
return "${day}-${month}-${year}"
}
// Getting hours and minute from string date in minutes
fun String.getMinuteOfDayFromServerTimeStamp(): Int{
val cal = Calendar.getInstance()
cal.time = this.getDateWithServerTimeStamp()!!
val hours = cal.get(Calendar.HOUR_OF_DAY)
val minutes = cal.get(Calendar.MINUTE)
return (hours*60 + minutes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment