Scala program to convert a string into date-time

Here, we are going to learn how to convert a string into date-time in Scala programming language?
Submitted by Nidhi, on May 30, 2021 [Last updated : March 11, 2023]

Scala - String to Date-Time Conversion

Here, we will create a format using SimpleDateFormat class. Then parse the specified date-time string into the date-time object using the parse() method and print the result on the console screen.

Scala code to convert a string into date-time

The source code to convert a string into a date-time is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to convert string into date-time

import java.text.SimpleDateFormat;

object Sample {
  def main(args: Array[String]) {

    val format = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    var result = format.parse("14-8-1988 10:20:30");

    println("Date time is: \n" + result);
  }
}

Output

Date time is: 
Sun Aug 14 10:20:30 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 a format for date and time using SimpleDateFormat class and then parsed the specified string into date-time and printed the result on the console screen.

Scala Date & Time Programs »





Comments and Discussions!

Load comments ↻





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