Know to handle Date Format in Java or Android is always a life saver, as Java libraries are not very easy to use when it comes to Date or Date formats. And one of the common problem all the Java or Android developers face is handling multiple date formats. So let me help you all using java.text.DateFormat
–
Custom DateFormat class
To handle multiple date the first step is to create a custom java.text.DateFormat
class
import java.text.FieldPosition; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Shailendra at Onetouchcode.com */ public class CustomDateFormat extends java.text.DateFormat { static final String FORMAT1 = "yyyy-MM-dd HH:mm:ss.SSS"; static final String FORMAT2 = "yyyy-MM-dd"; static final String FORMAT3 = "dd/MM/yyyy"; final SimpleDateFormat sdf1 = new SimpleDateFormat(FORMAT1); final SimpleDateFormat sdf2 = new SimpleDateFormat(FORMAT2); final SimpleDateFormat sdf3 = new SimpleDateFormat(FORMAT3); @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { throw new UnsupportedOperationException(); } @Override public Date parse(String source, ParsePosition pos) { int difference = source.length() - pos.getIndex(); if (difference == FORMAT1.length()) { return sdf1.parse(source, pos); } else if (difference == FORMAT2.length()) { return sdf2.parse(source, pos); } else { return sdf3.parse(source, pos); } } }
Date Parsing
After the creation of CustomDateFormat
class within your project, next or final step is to parse the date using this class
public Date parseDate(final String dateString){ CustomDateFormat cdf = new UniversalDateFormat(); //TODO change the timezone as per your requirement. cdf.setTimeZone(TimeZone.getDefault()); try { return udf.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } return null; }
So the above class is able to handle three different date formats and if the the format is not among them the above method will return null
but you can add another new format in the class and your parse methods will start supporting that newly added date format too.
That’s it.
Please share this article with your colleagues and friends.
Happy coding!!!
The post Java/Android – Handling multiple date formats using DateFormat appeared first on { OneTouchCode.com }.