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.
Program 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.
Program:
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)
}
}
Program to get date in Scala
Output
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.
Program to extract month as a number
Output
Formatting month string
We can use string formatting methods like toUpperCase and toLowerCase to extract month as an uppercase string or lowercase string.
Program:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer