aspose file tools*
The moose likes Java in General and the fly likes turn string date to number date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "turn string date to number date" Watch "turn string date to number date" New topic
Author

turn string date to number date

jon ruane
Greenhorn

Joined: Mar 08, 2007
Posts: 13
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
Marshal

Joined: Mar 22, 2005
Posts: 41526
    
  53
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).


Ping & DNS - my free Android networking tools app
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3446
    
  12
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


Joanne
jon ruane
Greenhorn

Joined: Mar 08, 2007
Posts: 13
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

Joined: Aug 05, 2005
Posts: 3446
    
  12
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 ?
 
Consider Paul's rocket mass heater.
 
subject: turn string date to number date