Convert String to Date in Java

In this example, I am attaching simple program about, How to Convert String to Date in Java.

StringToDate.java

package com.dineshkrish.date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 
* @author Dinesh Krishnan
*
*/
public class StringToDate {
public static Date convertStringToDate(String source, String format) {
Date convertedDate = null;
if((source != null && !source.isEmpty()) && (format != null && !format.isEmpty())) {
// Defining the DateFormate Object by passing Format
DateFormat dateFormat = new SimpleDateFormat(format);
try {
// Converting String to Date
convertedDate = dateFormat.parse(source);
} catch (ParseException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}	
return convertedDate;
}
public static void main(String[] args) {
System.out.println("How to Convert String to Date in Java");
System.out.println("---------------------------------------");
System.out.println(convertStringToDate("24/11/2016", "dd/MM/yyyy"));
System.out.println(convertStringToDate("24-11-2016", "dd-MM-yyyy"));
System.out.println(convertStringToDate("24.11.2016", "dd.MM.yyyy"));
}
}

Output

Thu Nov 24 00:00:00 IST 2016
Thu Nov 24 00:00:00 IST 2016
Thu Nov 24 00:00:00 IST 2016

References

1. Java API Documentation
2. java.util.Date API
3. java.text.DateFormat API

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *