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

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)

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)


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


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 »


Comments and Discussions!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.