Post Reply 
 
Thread Rating:
  • 1 Votes - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Java code to convert String containing a date to a Date object and vice versa
02-06-2011, 08:49 AM
Post: #1
Java code to convert String containing a date to a Date object and vice versa
Java code using SimpleDateFromat convert the Date in String format to Date object and vice verse Convert Date object into a String .If the String fails to parse as a Date, return null or if the SimpleDateFormat is not valid it will return null.

Find below the code with example.


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class JavaDateConvertion {

public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");
public static void main(String[] args) {
Date d=getDate("03/21/2008",DATE_FORMAT);
System.out.println(d);

System.out.println(getDateStr(new Date(),DATE_FORMAT));
}

/**
* convert String containing a date to a Date object.
* If the String fails to parse as a Date, return null.
* @param dateStr a String, presumed to be in format df
* @return a Date object, or null
*/
public static Date getDate(String dateStr, SimpleDateFormat df) {
Date date = null;
df.setLenient(true);
if (dateStr == null)
date = null;
else {
try {
date = df.parse(dateStr);
} catch (ParseException e) {
date = null;
}
}
return date;
}
/**
* This method converts a Date object into a String
* using the specified format
* @param date
* @param format is the format of the date
* @return a String in desired format, or null if date is null.
*/
public static String getDateStr(Date date, SimpleDateFormat df) {
df.setLenient(true);
if (date != null)
return df.format(date);
return null;
}
}
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:



Send your comments, Suggestions or Queries regarding this site at info@tutorials4u.net

Copyright © 2010 Tutorials4u.net All Rights Reserved