Today we will look at one very useful utility class named DateConverter which is part of the thoughtworks xstream library . This class can parse date from almost any given format. In the below given example the DateConverter class takes two constructor arguments, first one is default date format and second one is an array of all possible formats this converter can accept.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
package com.ourownjava.corejava.util; import junit.framework.Assert; import org.junit.Test; import com.thoughtworks.xstream.converters.basic.DateConverter; /** * * @author ourownjava.com * */ public class DateParserExample { private DateConverter converter = new DateConverter("dd-MMM-yyyy", new String [] {"dd-MMM-yyyy", "dd-MMM-yy", "yyyy-MMM-dd", "yyyy-MM-dd", "yyyy-dd-MM", "yyyy/MM/dd", "yyyy.MM.dd", "MM-dd-yy", "dd-MM-yyyy"}); private Object parse(String dateString){ Object o = converter.fromString(dateString); System.out.println(converter.toString(o)); return o; } @Test public void testddMMMyyyy(){ Assert.assertTrue(parse("12-May-2011") instanceof java.util.Date); } @Test public void testddMMyy(){ Assert.assertTrue(parse("12-May-11") instanceof java.util.Date); } @Test public void testyyyyMMMdd(){ Assert.assertTrue(parse("2011-May-09") instanceof java.util.Date); } @Test public void testyyyyMMdd(){ Assert.assertTrue(parse("2011-01-09") instanceof java.util.Date); } @Test public void testyyyyddMM(){ Assert.assertTrue(parse("2011-30-09") instanceof java.util.Date); } @Test public void testyyyyMMdd2(){ Assert.assertTrue(parse("2011/09/30") instanceof java.util.Date); } @Test public void testyyyyMMdd3(){ Assert.assertTrue(parse("2011.09.30") instanceof java.util.Date); } @Test public void testMMddyyyy(){ Assert.assertTrue(parse("09-30-2011") instanceof java.util.Date); } @Test public void testddMMyyyy(){ Assert.assertTrue(parse("31-12-2011") instanceof java.util.Date); } } |
Pingback: Date formatting in java | Clean Java