Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to get a readable date from a long (timestamp) in scala

Tags:

apache

scala

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"

like image 240
Anneso Avatar asked Nov 20 '18 12:11

Anneso


2 Answers

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
like image 108
pme Avatar answered Oct 16 '22 08:10

pme


Don't overthink it: nothing wrong with just new Date(start).toString

like image 31
Dima Avatar answered Oct 16 '22 10:10

Dima