How to convert date from one format to another in java/android


/**
 * @param date
 * date in String
 * @param fromFormat
 * format of your <b>date</b> eg: if your date is 2011-07-07
 * 09:09:09 then your format will be <b>yyyy-MM-dd hh:mm:ss</b>
 * @param toFormat
 * format to which you want to convert your <b>date</b> eg: if
 * required format is 31 July 2011 then the toFormat should be
 * <b>d MMMM yyyy</b><br/>
 *<b>Note: </b> For date formatting code refer <a href="https://androidsnippets.wordpress.com/2012/08/28/date-format-codes-in-java-simpledateformat-class/">Date Formats</a> and {@link SimpleDateFormat}
 *
 * @return formatted date <br/>
 * empty string if you provide invalid <b>fromFormat</b> or <b>toFormat</b>.
 */
 public static String convertDate(String date, String fromFormat,String toFormat)
 {
 String formattedDate = "";
 try {
 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fromFormat);
 Date d = simpleDateFormat.parse(date);
 Calendar calendar = Calendar.getInstance();
 calendar.setTime(d);

simpleDateFormat = new SimpleDateFormat(toFormat);
 simpleDateFormat.setCalendar(calendar);
 formattedDate = simpleDateFormat.format(calendar.getTime());

} catch (Exception e)
 {
 if(e!=null)
 e.printStackTrace();
 }

return formattedDate;
 }
Advertisements

Tags: , , , , , , , ,

About krishjlk

http://www.facebook.com/krishna.kanth.121

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: