Parsing a single date like 30 March 1970 can be achieve by using parse() Method of DateFormat and SimpleDateFormat classes.
Date
Java String to Single Date Example
- import java.text.SimpleDateFormat;
- import java.util.Date;
- public class StringToDateExample1 {
- public static void main(String[] args)throws Exception {
- String sDate1="31/12/1998";
- Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);
- System.out.println(sDate1+"\t"+date1);
- }
- }
Convert Multiple dates to date format
Example of converting multiple format dates in date format from Arraylist, database (dd/mm/yyyy, mm/dd/yyyy, EEE MMM d yyyy)
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.text.DateFormat;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Arrays;
- import java.util.List;
- public class StringToMultipleDateExample {
- public static void main(String[] args)throws Exception {
- SimpleDateFormat sdf[] = new SimpleDateFormat[] {
- new SimpleDateFormat("dd/MM/yyyy"),
- new SimpleDateFormat("dd/MM/yyyy HH:mm"),
- new SimpleDateFormat("dd/MM/yyyy hh:mm"),
- new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a"),
- new SimpleDateFormat("dd-MM-yyyy"),
- new SimpleDateFormat("EEE MMM d yyyy"),
- new SimpleDateFormat("EEE MMM d yyyy HH:mm:ss 'GMT'Z"),
- new SimpleDateFormat("EEE MMM dd yyyy hh:mm a"),
- new SimpleDateFormat("EEE MMM d hh:mm"),
- new SimpleDateFormat("EEE MMM d hh:mm:ss a zzz yyyy"),
- new SimpleDateFormat("EEEEEE MMMMMM dd yyyy h:mm a")
- };
- // Adding dates in multiple format
- List<String> list = Arrays.asList(new String[] {
- "11-03-2021",
- "11/03/2021 12:01:08 PM",
- "11/03/2021 12:01",
- "Thu Mar 11 2021",
- "Thu Mar 11 2021 12:01:08 GMT+0530",
- "Thu Mar 11 2021 12:01 PM",
- "Thu Mar 11 12:01:08 PM IST 2021",
- "Thursday March 11 2021 12:01 PM" });
- //print all received dates from ParseDate() Funtion and Print Them
- for (int i = 0; i < list.size(); i++) {
- System.out.println(parseDate(list.get(i), sdf).toString()+"\n");
- }
- }
- public static Date parseDate(String value, DateFormat... formatters) {
- Date date = null;
- for (DateFormat formatter : formatters) {
- try {
- date = formatter.parse(value);
- break;
- } catch (ParseException e) {
- }
- }
- return date;
- } }
Comments
Post a Comment