Q:

How to convert a string to date in Scala?

belongs to collection: Scala String Programs

0

String in Scala

String is a collection of characters that is mutable, i.e. its contents cannot be modified.

Syntax for creating string:

    val string_name : String = "string_value"

Example of string:

    val string = "Includehelp"

Date in Scala

Date is a variable that stores the date-time information for the date. It uses the Calendar class present in java calendar library imported using import java.util.calendar.

Convert string to date in Scala

As Scala uses the java-based date library we can use methods in java to convert string to date. So, here we will use the parse method.

Syntax to convert a string to date using parse method:

    val date = date_format_name.parse(string)

All Answers

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

Program to convert string to date

// converting string to date in Scala
import java.text.SimpleDateFormat
import java.util.Date

object MyObject {
    def main(args: Array[String]) {
        val string = "2020-06-20"
        println("String is " + string)
        
        val dateformat = new SimpleDateFormat("yyyy-MM-dd")
        val date = dateformat.parse(string)
        
        println("Converted date is " + date)
    }
}

Output:

String is 2020-06-20
Converted date is Sat Jun 20 00:00:00 GMT 2020

Explanation:

Here, we have converted the string to date in Scala. For this, we have used the parse method in simpleDateFormat. After conversion, we have printed the date using the println statement.

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 convert hex string to int in Scala?... >>
<< How to convert byte array to string in Scala?...