0

I want to parse the string data "2016-06-08T10:27:17.369000000000Z", with

import java.text.SimpleDateFormat

import scala.util.Try
object TimeParse extends App {
  val raw = "2016-06-08T10:27:17.369000000000Z"
  private def parseDate(inputdate: String) = {
    val fromUser = new SimpleDateFormat("""yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSSSS'Z'""")
    val myFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss")
    Try(myFormat.format(fromUser.parse(inputdate)))
  }

  val r = parseDate(raw)
  println("r - " + r)
}

But output:
r - Success(2016年06月04日 04:27:29)

If I remove millis format, it will be right, as this:

object TimeParse extends App {
  val raw = "2016-06-08T10:27:17Z"
  private def parseDate(inputdate: String) = {
    val fromUser = new SimpleDateFormat("""yyyy-MM-dd'T'HH:mm:ss'Z'""")
    val myFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss")
    Try(myFormat.format(fromUser.parse(inputdate)))
  }

  val r = parseDate(raw)
  println("r - " + r)
}

Output :
r - Success(2016年06月08日 10:27:17) why millisecond will get a fail result?

LoranceChen
  • 2,453
  • 2
  • 22
  • 48

1 Answers1

2

Well, the SimpleDateFormat does not the seconds and milliseconds values as a decimal number.

It processes them separately, and therefore 17.369000000000 is not 17 seconds and 369 milliseconds but 17 seconds and 369_000_000_000 milliseconds.

The milliseconds value is then truncated to int and therefore is interpreted as -367_187_456 milliseconds, which is added to your date value (2016-06-08T10:27:17) and so you get a timestamp that is before your actual date.

See also java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

Community
  • 1
  • 1
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34
  • I suddenly hit on how does 369_000_000_000 can truncated to -367_187_456 ? – LoranceChen Jun 13 '16 at 05:42
  • @LoranceChen SimpleDateFormat reads this number as long value and then casts it to int (something like `System.out.println((int) 369_000_000_000L);`, which prints out `-367187456`) – Thomas Kläger Jun 13 '16 at 10:37