Home »
Scala »
Scala Programs
Scala program to convert a string into a date
Here, we are going to learn how to convert a string into a date in Scala programming language?
Submitted by Nidhi, on May 30, 2021 [Last updated : March 11, 2023]
Scala – String to Date Conversion
Here, we will create a format using SimpleDateFormat class. Then parse specified date string into date object using parse() method and print the result on the console screen.
Scala code to convert a string into a date
The source code to convert a string into a date is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
// Scala program to convert a string into date
import java.text.SimpleDateFormat;
object Sample {
def main(args: Array[String]) {
val format = new SimpleDateFormat("dd-MM-yyyy");
var result = format.parse("14-8-1988");
println("Date is: \n" + result);
}
}
Output
Date is:
Sun Aug 14 00:00:00 GMT 1988
Explanation
Here, we used an object-oriented approach to create the program. And, we imported SimpleDateFormat class using the below statement,
import java.text.SimpleDateFormat;
Then we created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.
In the main() function, we created the format for a date using SimpleDateFormat class and then parsed the specified string into date and printed the result on the console screen.
Scala Date & Time Programs »