Home »
Scala »
Scala Programs
How to get date, month and year as string or number in Scala?
Here, we are going to learn how to extract the date and then convert it into string or number in the Scala programming language?
Submitted by Shivang Yadav, on April 24, 2020 [Last updated : March 10, 2023]
Scala – Getting Date, Month, and Year as String/Number
The "calendar" class handles working with date and time in Scala, the class generates the current time in the following format,
Thu Apr 23 06:10:37 GMT 2020
We can extract different parts like date, month, and year.
Scala code to get date
import java.util.Calendar
import java.text.SimpleDateFormat
object MyClass {
def main(args: Array[String]) {
val cal = Calendar.getInstance
val dateTime = cal.getTime
println("Full date information : " + dateTime)
val dateFormat = new SimpleDateFormat("dd")
val date = dateFormat.format(dateTime)
println("Date is : " + date)
val dateFormat2 = new SimpleDateFormat("MMM")
val month = dateFormat2.format(dateTime)
println("Month is : " + month)
val dateFormat3 = new SimpleDateFormat("YYYY")
val year = dateFormat3.format(dateTime)
println("Year is : " + year)
}
}
Output
Full date information : Fri Apr 24 16:59:22 GMT 2020
Date is : 24
Month is : Apr
Year is : 2020
Extracting month number
In Scala, we can extract the string in the form of the number instead of a string. The date format provides an option for this too.
The format "MM" does our work.
Scala code to extract month as a number
import java.util.Calendar
import java.text.SimpleDateFormat
object MyClass {
def main(args: Array[String]) {
val cal = Calendar.getInstance
val dateTime = cal.getTime
val dateFormat = new SimpleDateFormat("MM")
val month = dateFormat.format(dateTime)
println("Month number is : " + month)
}
}
Output
Month number is : 04
Formatting month string
We can use string formatting methods like toUpperCase and toLowerCase to extract month as an uppercase string or lowercase string.
Scala code to format month as string
import java.util.Calendar
import java.text.SimpleDateFormat
object MyClass {
def main(args: Array[String]) {
val cal = Calendar.getInstance
val dateTime = cal.getTime
val dateFormat = new SimpleDateFormat("MMM")
val month = dateFormat.format(dateTime).toUpperCase
println("Month is : " + month)
val Lmonth = dateFormat.format(dateTime).toLowerCase
println("Month is : " + Lmonth)
}
}
Output
Month is : APR
Month is : apr
Scala String Programs »