How to use SimpleDateFormat with Calender In Java
- In 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.
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:
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