Two Laptop Bag*
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "turn string date to number date" Watch "turn string date to number date" New topic

turn string date to number date

jon ruane

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

Joined: Mar 22, 2005
Posts: 41063
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

Joined: Aug 05, 2005
Posts: 3419
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
and then do

jon ruane

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) {

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

Joined: Aug 05, 2005
Posts: 3419
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 ?
It is sorta covered in the JavaRanch Style Guide.
subject: turn string date to number date
Similar Threads
Changing the date format
How to manipulate date / time using Calendar and then put the modified data inside the Date class?
Convert String to Date
How to display date in Daylight Savings
Custom Date class and Appointment class