How to convert a string to date in Scala?

Scala | Converting string to date: Here, we are going to learn how to convert a string to date in Scala and methods with syntax and example?
Submitted by Shivang Yadav, on May 21, 2020 [Last updated : March 10, 2023]

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)

Scala code 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.

Scala String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.