How to get date and timestamp in Scala?

In this article, we will learn how to get date and timestamp in scale. to get the current date and timestamp we can use java.time package. This package provides data and time features that are introduced in Java 8. We can use the LocalDateTime class to get the date and time and we can format it according to our needs and requirements using DateTimeFormatter. This approach is simple and easy for formatting date and time data.

Syntax:

LocalDateTime.now()

Let us try to understand this using better examples.

Example 1:

import java.time.LocalDateTime

object Example1 {
def main(args: Array[String]): Unit = {
val currentDateTime: LocalDateTime = LocalDateTime.now()
println("Complete Time: " + currentDateTime)
}
}

The following code fetches the current date and time from the LocalDateTime.now() method and prints it out.

Output:

output

Example 2:

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

object Example2 {
def main(args: Array[String]): Unit = {
val currentDateTime: LocalDateTime = LocalDateTime.now()
val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
val formattedDate: String = currentDateTime.format(formatter)
println("Current Date: " + formattedDate)
}
}

This Scala code uses LocalDateTime.now() to get the current date and time, then converts it to “dd-MM-yyyy” using a DateTimeFormatter, stores the formatted date in a string called formattedDate, and prints it.

Output:

output

Example 3:

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

object Example3 {
def main(args: Array[String]): Unit = {
val currentDateTime: LocalDateTime = LocalDateTime.now()
val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss")
val formattedTime: String = currentDateTime.format(formatter)
println("Current Time: " + formattedTime)
}
}

Using LocalDateTime.now(), this Scala code gets the current time, converts it to “HH:mm:ss” format with the help of DateTimeFormatter, and next saves formatted time into a string named formattedTime and prints it.

Output:

output

Example 4:

import java.time.Instant

object Example4 {
def main(args: Array[String]): Unit = {
val currentTimestamp: Long = Instant.now().getEpochSecond()
println("Current Timestamp: " + currentTimestamp)
}
}

This code obtains the current timestamp in seconds since the start of Unix epoch (January 1, 1970, UTC) using Instant.now().getEpochSecond() and then prints it.

Output:

output