Write a Java program to extract date, time from the date string
This program takes a date string in a certain format, converts it to a Date object, and then formats it into a new date string with a different format.
- import java.util.*; and import java.text.*; import the necessary packages for using Date and SimpleDateFormat classes respectively.
- public class Extract_DateTime defines a public class named Extract_DateTime.
- public static void main(String[] args) is the main method that executes when the program runs.
- try and catch block are used to handle an exception in case the input date format is not valid.
- String str_date = "2014-06-08 10:30:25"; defines a String variable named str_date that stores a date string in the format of yyyy-MM-dd HH:mm:ss.
- Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str_date); creates a Date object by parsing the str_date string using the SimpleDateFormat class with a pattern of yyyy-MM-dd HH:mm:ss.
- String newstr_date = new SimpleDateFormat("MM/dd/yyyy,H:mm:ss").format(date); formats the date object date into a new date string with the pattern of MM/dd/yyyy, H:mm:ss using the SimpleDateFormat class, and assigns it to the string variable newstr_date.
- System.out.println(newstr_date); prints the newly formatted date string newstr_date to the console.
Source Code
import java.util.*;
import java.text.*;
public class Extract_DateTime
{
public static void main(String[] args)
{
try
{
String str_date = "2014-06-08 10:30:25";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str_date);
String newstr_date = new SimpleDateFormat("MM/dd/yyyy, H:mm:ss").format(date);
System.out.println(newstr_date);
}
catch (ParseException e)
{
e.printStackTrace();
}
}
}
Output
06/08/2014, 10:30:25