I have a list of values 12012
, 112013
, 52005
stored as strings and i need to convert them into Jan 2012, Nov 2013, May 2005 correspondingly. I know how I can do this using parsing the string and using the if
statement. Is there any efficient way?
Asked
Active
Viewed 5,212 times
0

Andrei Vasilev
- 597
- 5
- 18
- 37
-
6Check out `SimpleDateFormat`. – Sotirios Delimanolis Oct 10 '13 at 17:15
-
1possible duplicate of [How to convert a date String to a Date or Calendar object?](http://stackoverflow.com/questions/43802/how-to-convert-a-date-string-to-a-date-or-calendar-object) – jmj Oct 10 '13 at 17:15
-
2https://google.com/search?q=java+convert+string+to+date has as 1st hit http://stackoverflow.com/questions/4216745/java-string-to-date-conversion – BalusC Oct 10 '13 at 17:17
3 Answers
4
Something like this might work:
String val = "12012";
int numVal = Integer.parseInt(val);
int year = numVal % 10000;
int month = numVal / 10000;
... create a date from that ...
I don't know whether you want a java Date
or Calendar
or whatever.
Calendar cal = Calendar.getInstance().clear();
cal.set(year, month-1, 1);
Date date = cal.getTime();
Or Joda Time for a date without a timezone:
LocalDate dt = new LocalDate(year, month, 1);

Lee Meador
- 12,829
- 2
- 36
- 42
3
Using SimpleDateFormat pattern you can easily do that: Try following simple code:
String str="12012";//112013 , 52005
SimpleDateFormat format=new SimpleDateFormat("Myyyy");
SimpleDateFormat resFormat=new SimpleDateFormat("MMM yyyy");
Date date=format.parse(str);
System.out.println(resFormat.format(date));

Masudul
- 21,823
- 5
- 43
- 58
-
I'm not sure this would work as you have two types of dates given in the example Myyyy and MMyyyy, if you try your solution with 112013 it will print : jan. 12013 instead of nov 2013 – Frederic Close Oct 10 '13 at 17:39
3
As you have strings representing dates that have two different formats Myyyy and MMyyyy, with a SimpleDateFormat
I'm not sure you can avoid an if statement, that's how I would do it:
SimpleDateFormat sdf1 = new SimpleDateFormat("Myyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMyyyy");
Date d = null;
if(5 == s.length()){
d = sdf1.parse(s);
}else if(6 == s.length()){
d = sdf2.parse(s);
}

Frederic Close
- 9,389
- 6
- 56
- 67