Skip to content

Instantly share code, notes, and snippets.

@hisetu
Last active July 3, 2022 10:10
Show Gist options
  • Save hisetu/e8449735129364e26cec1f131516134c to your computer and use it in GitHub Desktop.
Save hisetu/e8449735129364e26cec1f131516134c to your computer and use it in GitHub Desktop.
Kotlin Extensions
fun Activity.getStringFromIntentOrState(field: String, savedInstanceState: Bundle?): String? =
when {
intent.getStringExtra(field) != null -> intent.getStringExtra(field)
savedInstanceState?.getString(field) != null -> savedInstanceState.getString(field)
else -> null
}
fun Activity.hideKeyboard() {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)
?.let { imm ->
val view = currentFocus ?: View(this)
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
fun Fragment.hideKeyboard() {
activity?.hideKeyboard()
}
fun LocalDate.toLocalDateTime(): LocalDateTime {
return LocalDateTime.of(year, monthValue, dayOfMonth, 0, 0)
}
fun LocalDateTime.getThisWeekDays(): List<LocalDateTime> {
val fieldISO = WeekFields.of(Locale.getDefault()).dayOfWeek()
return (1L..7L).map { with(fieldISO, it) }
}
fun LocalDateTime.getThisWeekDays(): List<LocalDateTime> {
val fieldISO = WeekFields.of(Locale.TRADITIONAL_CHINESE).dayOfWeek()
return (1L..7L).map { with(fieldISO, it) }
}
fun LocalDateTime.getThisMonthStartEndDay(): Pair<LocalDateTime, LocalDateTime> {
val date = toLocalDate()
val start = date.withDayOfMonth(1)
val end = date.withDayOfMonth(date.month.length(date.isLeapYear))
return start.toLocalDateTime() to end.toLocalDateTime()
}
fun LocalDateTime.getThisMonthAllDays(): List<LocalDateTime> {
val (start, end) = LocalDateTime.now().getThisMonthStartEndDay()
return (start.dayOfMonth..end.dayOfMonth).map {
LocalDate.now().withDayOfMonth(it)
}.map { it.toLocalDateTime() }
}
fun File.makeZip(filePaths: List<String>) {
ZipOutputStream(BufferedOutputStream(FileOutputStream(this))).use { out ->
for (file in filePaths) {
FileInputStream(file).use { fi ->
BufferedInputStream(fi).use { origin ->
val entry = ZipEntry(file.substring(file.lastIndexOf("/") + 1))
out.putNextEntry(entry)
origin.copyTo(out, 1024)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment