LoginSignup
0
0

DateTimeFormatter.formatで型「M/d」指定すると「01」でも「1」でも変換可能

Posted at

これは何

java.time.DateTimeFormatterのString->日付型の変換が結構柔軟で助かった話です!

型に「yyyy/M/d」と指定すれば、例えば日付が「01」でも「1」でも型変換してくれるようになります。

何がええんや??

「2022/1/1」と「2022/1/01」どちらも変換してくれて、「2022年1月1日」を表すようになります。

「yyyy/MM/dd」「yyyy/M/d」で分けて変換しないといけないのかなと思っていたのですが、「yyyy/M/d」だけで0埋めアリ/ナシ共に変換してくれるのが便利なところです。

[:contents]

公式

[https://docs.oracle.com/javase/jp/8/docs/api/java/time/format/DateTimeFormatter.html:embed:cite]

動作確認

以下テストで全てOKでした。

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

class DateTimeFormatterTest {

    private val formatter = DateTimeFormatter.ofPattern("yyyy/M/d")

    @Test
    fun `2022_01_01OK`() {
        val result = LocalDate.parse("2022/01/01", formatter)
        assertEquals(LocalDate.of(2022,1,1), result)
    }

    @Test
    fun `2022_1_01OK`() {
        val result = LocalDate.parse("2022/1/01", formatter)
        assertEquals(LocalDate.of(2022,1,1), result)
    }

    @Test
    fun `2022_01_1OK`() {
        val result = LocalDate.parse("2022/01/1", formatter)
        assertEquals(LocalDate.of(2022,1,1), result)
    }

    @Test
    fun `2022_11_11OK`() {
        val result = LocalDate.parse("2022/11/11", formatter)
        assertEquals(LocalDate.of(2022,11,11), result)
    }

    @Test
    fun `2022_11_011OK`() {
        val result = LocalDate.parse("2022/11/011", formatter)
        assertEquals(LocalDate.of(2022,11,11), result)
    }

    @Test
    fun `2022_11_111(存在しない日付)での時フォマットできない`() {
        assertThrows<DateTimeParseException> { LocalDate.parse("2022/11/111", formatter) }
    }

    @Test
    fun `202211111形式違いの時フォマットできない`() {
        assertThrows<DateTimeParseException> { LocalDate.parse("202211111", formatter) }
    }

}

より詳細な記事

[https://www.ne.jp/asahi/hishidama/home/tech/java/DateTimeFormatter.html:title]

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0