Created
June 10, 2019 06:22
-
-
Save jabaraster/c5414afccb24ca751db38553afcbd0b8 to your computer and use it in GitHub Desktop.
カレンダ整形問題:Kotlin版
This file contains hidden or 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.time.LocalDate | |
import java.time.Month | |
import java.time.temporal.ChronoUnit | |
import java.util.GregorianCalendar | |
import java.util.Locale | |
fun main() { | |
val now = LocalDate.now() | |
println(Main.formatMonthCalendar(now.year, now.month)) | |
} | |
object Main { | |
fun formatMonthCalendar(pYear: Int, pMonth: Month): String { | |
val fst = LocalDate.of(pYear, pMonth.value, 1) | |
val last = fst.plus(1, ChronoUnit.MONTHS).minusDays(1) | |
val offset = if (fst.dayOfWeek.value == 0) 1 else fst.dayOfWeek.value | |
val head = SimpleDateFormat("MMMMM Y", Locale.ENGLISH).format(GregorianCalendar(pYear, pMonth.value, 1).time) | |
val head2 = "Su Mo Tu We Th Fr Sa" | |
return listOf(centering(head, head2.length)) | |
.plus(listOf(head2)) | |
.plus((1..offset).map { null } | |
.plus(fst.dayOfMonth..last.dayOfMonth) | |
.chunked(7).map { week -> | |
week.joinToString(separator = " ", transform = ::toS) | |
}) | |
.joinToString(separator = "\n") | |
} | |
private fun centering(s: String, lineWidth: Int): String { | |
val l = (lineWidth - s.length ) / 2 | |
return (1..l).map { ' ' }.joinToString(separator = "") + s | |
} | |
private fun toS(day: Int?): String { | |
return when { | |
day == null -> " " | |
day < 10 -> " $day" | |
else -> day.toString() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment