Scala Convert String to Timestamp

1. Introduction

Converting a string to a timestamp is a common requirement in many Scala applications, especially those dealing with data processing and manipulation. This process involves parsing a string that represents a date and time into a Timestamp object. In Scala, there are multiple ways to achieve this, each suitable for different contexts. This blog post will demonstrate how to convert a string to a timestamp in Scala.

2. Program Steps

1. Define a string that represents a date and time.

2. Use different methods to convert this string into a Timestamp, including using Java's SimpleDateFormat and Scala's built-in methods.

3. Print the resulting timestamps to verify the conversion.

4. Execute the program to observe the behavior of each method.

3. Code Program

import java.text.SimpleDateFormat import java.sql.Timestamp object StringToTimestampDemo extends App { val dateTimeString = "2021-12-01 10:15:30" // Using SimpleDateFormat val format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val timestamp1 = new Timestamp(format.parse(dateTimeString).getTime) println(s"Using SimpleDateFormat: $timestamp1") // Using java.time.LocalDateTime (Scala 2.12 and above) import java.time.LocalDateTime import java.time.format.DateTimeFormatter val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val localDateTime = LocalDateTime.parse(dateTimeString, formatter) val timestamp2 = Timestamp.valueOf(localDateTime) println(s"Using LocalDateTime: $timestamp2") } 

Output:

Using SimpleDateFormat: 2021-12-01 10:15:30.0 Using LocalDateTime: 2021-12-01 10:15:30.0 

Explanation:

1. The SimpleDateFormat class from Java's standard library is used to parse the string into a Date object, which is then converted to a Timestamp.

2. With java.time.LocalDateTime (available in Scala 2.12 and later), we first parse the string into a LocalDateTime object using DateTimeFormatter, and then convert it to a Timestamp using Timestamp.valueOf.

3. Both methods require specifying the date-time pattern ("yyyy-MM-dd HH:mm:ss") to correctly parse the string.

4. The output shows the converted timestamps, which are identical in both cases.


Comments