Search code examples
scaladateparsinglocaldate

Parse dates from one format to another


I have an initial date as a String which I need to convert to date with a specific format. I tried to defined date format in a string and parse it, then I formatted it to the desired format. The problem is that I need a date as a final result. Here is the code I used:

  def parseDateToOriginal(date: String): String = {
    val initialDateFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy")
    val finalDateFormat = new SimpleDateFormat("yyyy-mm-dd")

    val result = finalDateFormat.format(initialDateFormat.parse(date))
    result
  }

So I need Date as the return type for this method. I tried to parse the result string to get a proper date but for some reason, the result defaults back to the original date format. How can I fix this problem?

Here is how I tried to parse it again:

val parsedDate = new SimpleDateFormat("yyyy-mm-dd").parse(parseDateToOriginal(date))

The result is of the pattern "EEE MMM dd hh:mm:ss zzz yyyy"


Solution

  • Try

    import java.time.LocalDateTime
    import java.time.format.DateTimeFormatter
    
    def parseDateToOriginal(date: String): String = {
      LocalDateTime
        .parse(date, DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss zzz yyyy"))
        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
    }
    

    which outputs

    parseDateToOriginal("Thu Jun 18 20:56:02 EDT 2009") // res2: String = 2009-06-18
    

    Note you have a bug in the format of finalDateFormat

    val finalDateFormat = new SimpleDateFormat("yyyy-mm-dd")
    

    You are using lowercase mm in the month positions, but should be upper case MM. Lowercase mm represents minutes, so it would erroneously result in res2: String = 2009-56-18 as outputs.