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"))
You can make use of Java 8 Date/Time API:
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
val format = "yyyyMMdd_HHmmss"
val dtf = DateTimeFormatter.ofPattern(format)
val ldt = LocalDateTime.of(2018, 1, 22, 10, 10, 43) // 20180122_101043
ldt.format(dtf)
To get the current time, use LocalDateTime.now()
.
You may use the java.time
library. For instance:
import java.time
val s: String = time.LocalDateTime.now().toString
println(s)
gives 2021-04-23T14:13:01.163869
. Then you need to manipulate the string, e.g.
time.LocalDateTime.now().toString.replace("T","_").replace("-","").replace(":","")
for 20210423_141639.769222
.