Xiaodong DENG, http://XD-DENG.com
System.currentTimeMillis
& Thread.sleep
java.util.Calendar
: Get Current Date & Timejava.text.SimpleDateFormat
: Convert Date/Time to Desired Format
System.currentTimeMillis
& Thread.sleep
¶System.currentTimeMillis
is a method from Java. It returns the current time in milliseconds [1].
Thread.sleep
is also a method from Java. It causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers [2].
val t1 = System.currentTimeMillis
Thread.sleep(500) // pause for 0.5 seconds (500 millisesonds)
val t2 = System.currentTimeMillis
t2 - t1
java.util.Calendar
: Get Current Date & Time¶import java.util.Calendar
val now = Calendar.getInstance.getTime
val nowInMillis = Calendar.getInstance.getTimeInMillis
println(now.getClass)
println(nowInMillis.getClass)
println(now.toString)
println(now.toInstant)
java.text.SimpleDateFormat
: Convert Date/Time to Desired Format¶It's common that we need to customize the format of date/time. For this purpose, we need tools like strftime
in Python. In Scala, we can use java.text.SimpleDateFormat
[3].
Using java.text.SimpleDateFormat
, we can create date/time formatters, then apply them on the java.util.Date
objects from Calendar.getInstance.getTime
, like the one (now
) we specified in the last section.
import java.text.SimpleDateFormat
// create the date/time formatters
val hour12Format = new SimpleDateFormat("hh")
val hour24Format = new SimpleDateFormat("HH")
val minuteFormat = new SimpleDateFormat("mm")
val amPmFormat = new SimpleDateFormat("a")
val dateFormat = new SimpleDateFormat("yyyy-MM-dd")
println(dateFormat.getClass)
println(now)
println(hour12Format.format(now) )
println(hour24Format.format(now) )
println(minuteFormat.format(now))
println(amPmFormat.format(now) )
println(dateFormat.format(now))
Similarly, we may need to convert strings into Date/Time. The tool we need is the same, java.text.SimpleDateFormat
. We simply need its another method, .parse
[4].
Using the formatter specified in the last section as example,
dateFormat.parse("2017-01-01")
We can specify another formatter in which we have richer information,
val full_dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
print(full_dateFormat.parse("2018-12-26 17:15:00"))
[1] https://docs.oracle.com/javase/7/docs/api/java/lang/System.html
[2] https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
[3] https://alvinalexander.com/scala/scala-number-nnumeric-date-formatting-casting-examples
[4] https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html