Q:

How to get date, month and year as string or number in Scala?

belongs to collection: Scala String Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to get date in Scala

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)
    }
}

Output

Month is : APR
Month is : apr

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to replace a regular expression pattern in a s... >>
<< How to left-trim and right-trim strings in Scala?...