0

I want to split Japanese date which is in format "2020年7月" into separate array so that can get the year and month from that.

I tried SimpleDateFormatter to format Japanese date with and have the year and date separated with "/"but the output is wrong:

Tried this code:

   val inputFormat = SimpleDateFormat("YYYY年M月")
   val date = inputFormat.parse("2020年7月")
   val outputText = SimpleDateFormat("YYYY/MM").format(date)

input :2020年7月 output:2020/12

Can anyone help me in this?

  • Is the output example the expected / desired one or the actual wrong one? – deHaar Jul 09 '20 at 13:26
  • 1
    use lowercase `y` for year – IR42 Jul 09 '20 at 13:27
  • 1
    or use `u` for a year – deHaar Jul 09 '20 at 13:34
  • 2
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `YearMonth` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jul 09 '20 at 13:47

1 Answers1

1

You should be using java.time for this because the datetime classes from java.util are outdated (but still not deprecated).

The following example shows a way using a java.time.format.DateTimeFormatter for parsing a String formatted according to a certain pattern and a java.time.YearMonth, a class obviously designed for the purpose of creating a month in a year without respect to a day of month:

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

fun main() {
    val jpYearMonth = "2020年7月"
    val japaneseDtf = DateTimeFormatter.ofPattern("uuuu年M月")
    val yearMonth = YearMonth.parse(jpYearMonth, japaneseDtf)
    println(yearMonth.format(DateTimeFormatter.ofPattern("uuuu/MM")))
}

In order to achieve your desired output this code has to use a different DateTimeFormatter defining the output pattern because the default pattern (internal use when you just println(yearMonth)) would be hyphon-separated (2020-07):

2020/07
deHaar
  • 17,687
  • 10
  • 38
  • 51
  • @OleV.V. Right, I just wanted to try this myself (never did before) and then I shared the result without checking for duplicates. My fault... – deHaar Jul 09 '20 at 13:38
  • @OleV.V. That's the *era* I'm currently in... I will try to remind myself about the check for duplicates. The `YearMonth` is even cooler, anyway. – deHaar Jul 09 '20 at 13:43
  • @OleV.V. I just found some time to follow your advice. Unfortunately, the output by using a `DateTimeFormatter.ofPattern("uuuu/MM")` doesn't look like a japanese era ;-) . I'm interested in possibilities of creating a `JapaneseDate` or `JapaneseEra`, but I doubt finding time for it today. – deHaar Jul 10 '20 at 06:32
  • 1
    @OleV.V. Maybe something to ask in a different question... Later on... – deHaar Jul 10 '20 at 06:56