How to Convert String to Date Time in Scala? Last Updated : 08 Apr, 2024 Comments Improve Suggest changes Like Article Like Report In this article, we will learn how to convert String to DateTime in Scala. Converting String to DateTime consists of parsing a textual representation of date and time into a structured DateTime object for further manipulation and processing in Scala programs. Table of Content Using SimpleDateFormatUsing SimpleDateFormat with CalenderUsing Simple ParsingUsing Regular Expressions Using SimpleDateFormatIn this approach, we are using the SimpleDateFormat class from Java's standard library to parse a user-inputted date and time string (userInput) in the format "yyyy-MM-dd HH:mm:ss" into a Date object (res). The SimpleDateFormat object (dFormat) is initialized with the desired date-time format, and the parse method is used to convert the string into a Date object based on this format. Finally, the parsed Date object is printed to the console using println.In the below example, the SimpleDateFormat library is used to convert String to date time. Scala // importing necessary classes from Java import java.text.SimpleDateFormat import java.util.Date // Creating object GFG object GFG { // Main method def main(args: Array[String]): Unit = { // Input string representing date and time val userInput = "2024-03-27 13:30:00" // Creating SimpleDateFormat object with the desired date-time format val dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // Parsing the input string to obtain a Date object val res = dFormat.parse(userInput) // Printing the parsed Date println("Parsed Date: " + res) } } Output: Using SimpleDateFormat with CalenderIn this approach, we are using a combination of SimpleDateFormat and Calendar classes from the Java standard library to parse a date and time string ("yyyy-MM-dd HH:mm:ss") into a Date object. The SimpleDateFormat instance dFormat is used to specify the date-time format for parsing. The Calendar instance cal is then used to set the parsed date and time values, which are obtained as a Date object (res) and printed to the console. In the below example, the SimpleDateFormat with Calender is used to convert String to date time. Scala import java.text.SimpleDateFormat import java.util.Calendar // Creating Objext object GFG { // Main Method def main(args: Array[String]): Unit = { // Input string representing date and time val dInput = "2024-03-27 13:30:00" // Creating a SimpleDateFormat object to parse the input string val dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // Creating a Calendar instance to work with date and time val cal = Calendar.getInstance() // Parsing the input string to obtain a Date object cal.setTime(dFormat.parse(dInput)) // Getting the Date object from the Calendar instance val res = cal.getTime() // Printing the parsed date println("Parsed Date: " + res) } } Output: Using Simple ParsingIn this approach, we are using simple parsing techniques in Scala to convert a string representing a date ("2024-03-27") into a GregorianCalendar object. The simpleParse method splits the input string by hyphens and attempts to create a calendar object based on the parsed components (year, month, day). If successful, it returns an Option[GregorianCalendar] representing the parsed date; otherwise, it returns None. In the below example, the Simple Parsing is used to convert String to date time. Scala import java.util.{Calendar, GregorianCalendar} class GFG { def simpleParse(dateString: String): Option[GregorianCalendar] = { dateString.split("-").toList match { case yyyy :: mm :: dd :: Nil => try { Some(new GregorianCalendar(yyyy.toInt, mm.toInt - 1, dd.toInt)) } catch { case _: NumberFormatException => None } case _ => None } } } object GFG extends App { val parser = new GFG // Input string representing date val dInput = "2024-03-27" // Parse the input string using simple parsing val maybeDate = parser.simpleParse(dInput) // Print the parsed DateTime object maybeDate match { case Some(date) => println("Parsed DateTime: " + date.getTime) case None => println("Invalid date format") } } Output: Using Regular Expressions In this approach, we are using regular expressions (Regex) in Scala to match and extract date components from a string with a specific format (yyyy-MM-dd HH:mm:ss). The parseDate method checks if the input string matches the regex pattern and extracts the year, month, day, hour, minute, and second components. If the format is valid, it constructs a GregorianCalendar object based on the extracted components, otherwise returning None.In the below example, the Regular Expressions is used to convert String to date time. Scala import java.util.{Calendar, GregorianCalendar} import scala.util.matching.Regex object GFG { def parseDate(dateString: String): Option[GregorianCalendar] = { val dateRegex = """(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})""".r dateString match { case dateRegex(year, month, day, hour, minute, second) => try { Some(new GregorianCalendar(year.toInt, month.toInt - 1, day.toInt)) } catch { case _: NumberFormatException => None } case _ => None } } def main(args: Array[String]): Unit = { val dInput = "2024-03-27 13:30:00" val maybeDate = parseDate(dInput) maybeDate match { case Some(date) => println("Parsed DateTime: " + date.getTime) case None => println("Invalid date format") } } } Output: Comment More infoAdvertise with us Next Article How to Convert String to Date Time in Scala? G gpancomputer Follow Improve Article Tags : Java Scala Practice Tags : Java Similar Reads How to convert future string to string in Scala? In this article, we will convert future string to string in Scala. We use three different methods to convert future string to string in Scala. Table of Content What is the future string in Scala?Methods to convert future string to string in Scala:What is the future string in Scala?"Future" is a cons 4 min read How to convert String to structtype in Scala? In Scala, whenever one deals with structured data such as JSON or CSV, there is usually a need to convert strings into structured data types like "StructType". This is very important for efficient processing and analysis of data, particularly in big data setups where Apache Spark is mostly used. To 3 min read How to Convert String to Date in TypeScript ? In TypeScript, conversion from string to date can be done using the Date object and its method. We can use various inbuilt methods of Date object like new Date() constructor, Date.parse(), and Date.UTC.Table of ContentUsing new Date()Using Date.parse() Using Date.UTC()Using new Date()In this approac 2 min read How to Convert String to Date or Datetime in Polars When working with data, particularly in CSV files or databases, it's common to find dates stored as strings. If we're using Polars, a fast and efficient DataFrame library written in Rust (with Python bindings), we'll often need to convert these strings into actual date or datetime objects for easier 5 min read How to Convert Date to Numeric in R? In this article, we will discuss how to convert date to numeric in R Programming Language. Method 1: Using as.numeric() This function is used to convert date into numeric Syntax: as.numeric(date) where the date is the input date. Example: R data = as.POSIXct("1/1/2021 1:05:00 AM", format="%m/%d/%Y % 2 min read Convert string to datetime in Python with timezone Converting a string to a datetime in Python with timezone means parsing a date-time string and creating a timezone-aware datetime object. For example, a string like '2021-09-01 15:27:05.004573 +0530' can be converted to a Python datetime object that accurately represents the date, time and timezone. 2 min read How to convert DateTime to integer in Python Python provides a module called DateTime to perform all the operations related to date and time. It has a rich set of functions used to perform almost all the operations that deal with time. It needs to be imported first to use the functions and it comes along with python, so no need to install it s 2 min read How to Convert DateTime to UNIX Timestamp in Python ? Generating a UNIX timestamp from a DateTime object in Python involves converting a date and time representation into the number of seconds elapsed since January 1, 1970 (known as the Unix epoch). For example, given a DateTime representing May 29, 2025, 15:30, the UNIX timestamp is the floating-point 2 min read How to get date and timestamp in Scala? In this article, we will learn how to get date and timestamp in scale. to get the current date and timestamp we can use java.time package. This package provides data and time features that are introduced in Java 8. We can use the LocalDateTime class to get the date and time and we can format it acco 2 min read Java Program to Convert String to Date Given a string in date format, the task is to convert this String into an actual date. Here the main concept is the parse() method which helps in the conversion. Illustration: Input : string = "2018-10-28T15:23:01Z" Output: 2018-10-28T15:23:01Z Input : string = "28 October, 2018" Output: 2018-10-28D 4 min read Like