Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current timestamp in Scala as a string without spaces?

Tags:

scala

I want to get for example a string of the current time: "20180122_101043". How can I do this?

I can create a val cal = Calendar.getInstance() but I'm not sure what to do with it after.

like image 826
osk Avatar asked Jan 22 '18 09:01

osk


2 Answers

LocalDateTime is what you might want to use,

scala> import java.time.LocalDateTime
import java.time.LocalDateTime

scala> LocalDateTime.now()
res60: java.time.LocalDateTime = 2018-01-22T01:21:03.048

If you don't want default LocalDateTime format which is basically ISO format without zone info, you can apply DateTimeFormatter as below,

scala> import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatter

scala> DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm").format(LocalDateTime.now)
res61: String = 2018-01-22_01:21

Related resource - How to parse/format dates with LocalDateTime? (Java 8)

like image 200
prayagupa Avatar answered Sep 23 '22 02:09

prayagupa


Calendar is not the best choice here. Use:

  • java.util.Date + java.text.SimpleDateFormat if you have java 7 or below

    new SimpleDateFormat("YYYYMMdd_HHmmss").format(new Date)

  • java.time.LocalDateTime + java.time.format.DateTimeFormatter for java 8+ LocalDateTime.now.format(DateTimeFormatter.ofPattern("YYYYMMdd_HHmmss"))
like image 36
Sergii Lagutin Avatar answered Sep 21 '22 02:09

Sergii Lagutin