Skip to content

Instantly share code, notes, and snippets.

@darmawan01
Forked from maiconhellmann/DateExtension.kt
Created March 2, 2019 01:58
Show Gist options
  • Save darmawan01/a7e78c17c752441610270a256a2a2164 to your computer and use it in GitHub Desktop.
Save darmawan01/a7e78c17c752441610270a256a2a2164 to your computer and use it in GitHub Desktop.
Date extensions wrote in Kotlin
import java.text.SimpleDateFormat
import java.util.*
/**
* Pattern: yyyy-MM-dd HH:mm:ss
*/
fun Date.formatToServerDateTimeDefaults(): String{
val sdf= SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
return sdf.format(this)
}
fun Date.formatToTruncatedDateTime(): String{
val sdf= SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
return sdf.format(this)
}
/**
* Pattern: yyyy-MM-dd
*/
fun Date.formatToServerDateDefaults(): String{
val sdf= SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
return sdf.format(this)
}
/**
* Pattern: HH:mm:ss
*/
fun Date.formatToServerTimeDefaults(): String{
val sdf= SimpleDateFormat("HH:mm:ss", Locale.getDefault())
return sdf.format(this)
}
/**
* Pattern: dd/MM/yyyy HH:mm:ss
*/
fun Date.formatToViewDateTimeDefaults(): String{
val sdf= SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault())
return sdf.format(this)
}
/**
* Pattern: dd/MM/yyyy
*/
fun Date.formatToViewDateDefaults(): String{
val sdf= SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
return sdf.format(this)
}
/**
* Pattern: HH:mm:ss
*/
fun Date.formatToViewTimeDefaults(): String{
val sdf= SimpleDateFormat("HH:mm:ss", Locale.getDefault())
return sdf.format(this)
}
/**
* Add field date to current date
*/
fun Date.add(field: Int, amount: Int): Date{
val cal = Calendar.getInstance()
cal.time=this
cal.add(field, amount)
this.time = cal.time.time
cal.clear()
return this
}
fun Date.addYears(years: Int): Date{
return add(Calendar.YEAR, years)
}
fun Date.addMonths(months: Int): Date {
return add(Calendar.MONTH, months)
}
fun Date.addDays(days: Int): Date{
return add(Calendar.DAY_OF_MONTH, days)
}
fun Date.addHours(hours: Int): Date{
return add(Calendar.HOUR_OF_DAY, hours)
}
fun Date.addMinutes(minutes: Int): Date{
return add(Calendar.MINUTE, minutes)
}
fun Date.addSeconds(seconds: Int): Date{
return add(Calendar.SECOND, seconds)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment