Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.threeten.bp.format.DateTimeFormatter
- class DateFormatterBuilder {
- enum class DateTimeUnit {
- YEAR,
- MONTH,
- DAY
- }
- private var prefix: ((DateTimeUnit, Boolean) -> String)? = null
- private var suffix: ((DateTimeUnit) -> String)? = null
- private var leadingZero: Boolean = false
- private var yearFormat: ((Boolean) -> String)? = null
- private var monthFormat: ((Boolean) -> String)? = null
- private var dayFormat: ((Boolean) -> String)? = null
- val hyphened: DateFormatterBuilder
- get() {
- prefix = { unit, inMiddle ->
- if (inMiddle) {
- "-"
- } else {
- ""
- }
- }
- suffix = null
- return this
- }
- val slashed: DateFormatterBuilder
- get() {
- prefix = { unit, inMiddle ->
- if (inMiddle) {
- "/"
- } else {
- ""
- }
- }
- suffix = null
- return this
- }
- val japanese: DateFormatterBuilder
- get() {
- suffix = {
- when (it) {
- DateTimeUnit.YEAR -> "ๅนด"
- DateTimeUnit.MONTH -> "ๆ"
- DateTimeUnit.DAY -> "ๆฅ"
- }
- }
- prefix = null
- return this
- }
- val year: DateFormatterBuilder
- get() {
- yearFormat = {
- appendPrefixAndSuffix(if (leadingZero) "yyyy" else "y", DateTimeUnit.YEAR, it)
- }
- return this
- }
- val month: DateFormatterBuilder
- get() {
- monthFormat = {
- appendPrefixAndSuffix(if (leadingZero) "MM" else "M", DateTimeUnit.MONTH, it)
- }
- return this
- }
- val day: DateFormatterBuilder
- get() {
- dayFormat = {
- appendPrefixAndSuffix(if (leadingZero) "dd" else "d", DateTimeUnit.DAY, it)
- }
- return this
- }
- val withLeadingZero: DateFormatterBuilder
- get() {
- this.leadingZero = true
- return this
- }
- private fun appendPrefixAndSuffix(format: String, unit: DateTimeUnit, inMiddle: Boolean): String
- = "${prefix?.let { it(unit, inMiddle) } ?: ""}$format${suffix?.let { it(unit) } ?: ""}"
- fun build(): DateTimeFormatter {
- val sb = StringBuilder().apply {
- yearFormat?.let { append(it(this.length > 0)) }
- monthFormat?.let { append(it(this.length > 0)) }
- dayFormat?.let { append(it(this.length > 0)) }
- }
- return DateTimeFormatter.ofPattern(sb.toString())
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement