Last active
August 17, 2023 07:36
-
-
Save maiconhellmann/796debb4007139d50e39f139be08811c to your computer and use it in GitHub Desktop.
Date extensions wrote in Kotlin
This file contains 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.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 { | |
Calendar.getInstance().apply { | |
time = this@add | |
add(field, amount) | |
return time | |
} | |
} | |
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) | |
} |
Indeed, thank you
Thank you for the inspiration! Just used it here!
An even shorter version
private fun Date.add(field: Int, amount: Int): Date = Calendar.getInstance().let { calendar ->
calendar.time = this@add
calendar.add(field, amount)
return@let calendar.time
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The add function could be shortened to