skip to Main Content

My question is simple

If I do:

var start = System.currentTimeMillis

I get:

start: Long = 1542717303659

How should I do to get a string looking to something readable for a human eye?:

ex: “20/11/2018 13:30:10”

3

Answers


  1. You can use the java.time library like:

      val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")
      formatter.format(LocalDateTime.now)
    

    If you only have the timestamp, this solution gets a bit more complex:

    formatter.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis()), ZoneId.of("UTC")))
    

    Then I would take java.text.SimpleDateFormat :

    new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(System.currentTimeMillis())
    

    To get back to the Timestamp:

    new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse( "02/12/2012 12:23:44" ).getTime
    
    Login or Signup to reply.
  2. Don’t overthink it: nothing wrong with just new Date(start).toString

    Login or Signup to reply.
  3. You can use java.time library and get it in readable format as below one-liner.

    scala>  java.time.LocalDateTime.ofEpochSecond(System.currentTimeMillis/1000,0,java.time.ZoneOffset.UTC)
    res31: java.time.LocalDateTime = 2018-11-21T18:37:49
    
    scala>
    

    I’m just diving the Milliseconds by 1000, so that we get EpochSecond.

    For getting it back,

    scala> java.time.LocalDateTime.parse("2018-11-21T18:41:29").toEpochSecond(java.time.ZoneOffset.UTC)
    res40: Long = 1542825689
    
    scala>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search