Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

turn string date to number date

 
jon ruane
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
does anyone know of any classes that i could use to turn a String date into its number equivalent?

i need to split a string "20 Apr, 2007" into day month year, so this would return:

day = 20
month = 4,
year = 2007

iv used a mixture of split() and parseInt() to get the day and year, but im left with String "apr" which i need to turn into 4. any simple way without using a massive IF statement.
 
Ulf Dittmer
Rancher
Pie
Posts: 42966
73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's what the java.text.SimpleDateFormat class is for. It can transform strings to Date objects (parse method) and Date objects to string (format method).
 
Joanne Neal
Rancher
Pie
Posts: 3742
16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Converting a month string to a number will obviously be locale specific. I don't know if the standard API has a way of doing it, but if it doesn't, one way would be to set up a HashMap using the month strings as keys and the int values as values
i.e.
and then do
 
jon ruane
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
cheers guys. just thought id post the way i eventually did it:

SimpleDateFormat format = new SimpleDateFormat("dd MMM, yyyy");

try {
Date parsed = format.parse(str);
GregorianCalendar cal =
new GregorianCalendar(parsed.getDay(),parsed.getMonth (),parsed.getYear());
int day = (parsed.getDate());
int month = (parsed.getMonth()+1);
int year = (parsed.getYear()+1900);
System.out.println(day +" " + month + " "+ year);
} catch (ParseException e) {
e.printStackTrace();
}

i realise that the get() methods from Date are in fact depreciated, but i've been told that they will function fine in an application thats not going to be run on a machine running a different time zone.
 
Joanne Neal
Rancher
Pie
Posts: 3742
16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The recommended methods to use instead of the Date.getXXX() methods are all in the Calendar class. So, as you have a Calendar object, why don't you use them ?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic