How to use Simple Parsing In Java
- In 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.
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:
How to Convert String to Date Time in Scala?
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 SimpleDateFormat
- Using SimpleDateFormat with Calender
- Using Simple Parsing
- Using Regular Expressions