Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date format conversion using Java

I am having a date/time value in standard ISO 8601 format such as as 2010-07-26T11:37:52Z.

I want date in 26-jul-2010 (dd-mon-yyyy) format. How do I do it?

like image 853
Paresh Mayani Avatar asked Sep 23 '10 12:09

Paresh Mayani


People also ask

How do I change the date format from DD MM YYYY to Yyyymmdd in Java?

First you have to parse the string representation of your date-time into a Date object. DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = (Date)formatter. parse("2011-11-29 12:34:25"); Then you format the Date object back into a String in your preferred format.

What is YYYY format in Java?

yyyy is the pattern string to identify the year in the SimpleDateFormat class. Java 7 introduced YYYY as a new date pattern to identify the date week year. An average year is exactly 52.1775 weeks long, which means that eventually a year might have either 52 or 53 weeks considering indivisible weeks.


2 Answers

Construct two SimpleDateFormat objects. The first you parse() the value from into a Date object, the second you use to turn the Date object back into a string, e.g.

try {
  DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
  DateFormat df2 = new SimpleDateFormat("dd-MMM-yyyy");
  return df2.format(df1.parse(input));
}
catch (ParseException e) {
  return null;
}

Parsing can throw a ParseException so you would need to catch and handle that.

like image 186
locka Avatar answered Sep 20 '22 13:09

locka


Have you tried using Java's SimpleDateFormat class? It is included with the android SDK: http://developer.android.com/reference/java/text/SimpleDateFormat.html

like image 36
McStretch Avatar answered Sep 20 '22 13:09

McStretch