Last active
March 30, 2020 00:42
-
-
Save viniciusalvesmello/03915c54bd9d4fa7caff190d4971d2f1 to your computer and use it in GitHub Desktop.
Exemplos de como trabalhar com datas no 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.* | |
import java.util.concurrent.TimeUnit | |
fun String.stringToDate(format: String = "yyyy-MM-dd HH:mm:ss"): Date = | |
SimpleDateFormat(format, Locale.getDefault()).parse(this) | |
fun Date.dateToString(format: String = "yyyy-MM-dd HH:mm:ss"): String = | |
SimpleDateFormat(format, Locale.getDefault()).format(this) | |
infix fun Date.difHoursTo(dateTo: Date): Long = | |
TimeUnit.MILLISECONDS.toHours(dateTo.time - this.time) | |
infix fun Date.difMinutesTo(dateTo: Date): Long = | |
TimeUnit.MILLISECONDS.toMinutes(dateTo.time - this.time) | |
infix fun Date.difSecondsTo(dateTo: Date): Long = | |
TimeUnit.MILLISECONDS.toSeconds(dateTo.time - this.time) | |
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 = | |
add(Calendar.YEAR, years) | |
fun Date.addMonths(months: Int): Date = | |
add(Calendar.MONTH, months) | |
fun Date.addDays(days: Int): Date = | |
add(Calendar.DAY_OF_MONTH, days) | |
fun Date.addHours(hours: Int): Date = | |
add(Calendar.HOUR_OF_DAY, hours) | |
fun Date.addMinutes(minutes: Int): Date = | |
add(Calendar.MINUTE, minutes) | |
fun Date.addSeconds(seconds: Int): Date = | |
add(Calendar.SECOND, seconds) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment