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.
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)
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With