Two Laptop Bag
The moose likes Beginning Java and the fly likes Formatting Dates Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Formatting Dates" Watch "Formatting Dates" New topic

Formatting Dates

Madhavi Gupta

Joined: Jan 30, 2002
Posts: 5
I have a string for date pattern called dPattern which is of the form ""mm/dd/yyyy"(dPattern = ""mm/dd/yyyy").I use this pattern to make the SimpleDateFormat class as
SimpleDateFormat sd = new SimpleDateFormat(dPattern);
I take a String of the form ,say ex: ateStr = "09/12/2001";
Date dt = sd.parse(dateStr, new ParsePosition(0));
The date dt when turned as a String gives me a strange Date as Jan 2001.
Also, if I use it in the Gregorian Calendar to set the time and access the month, the month comes out as January.
Can you pl explain me the reason and also, tell me how to do it right??
Here is the total code::
dPattern = ""mm/dd/yyyy"
SimpleDateFormat sd = new SimpleDateFormat(dPattern);
Date dt = sd.parse(dateStr, new ParsePosition(0));
Calendar calendar = new GregorianCalendar();
int month = calendar.get(Calendar.MONTH) + 1;

Thanks in advance,
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

mm is for minutes.
MM is for month.
Chris Stehno
Ranch Hand

Joined: Feb 26, 2001
Posts: 180
Okay... so you want the date to look like:
correct. To do this, I would use the following code:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date today = new Date();
String todayStr = sdf.format(today);
which will give you the desired formatting ... to go the other way, simply use the single argument parse method:
Date nextDay = sdf.parse("02/26/2002");
which will give you the proper Date object.
One thing I noticed in your formatting string ... you are using m (lower case) for the month, you should be using M (upper case), lower case is for minutes. (you also seem to have two quotes at the start of your pattern string.
Hope this helps.
[ February 25, 2002: Message edited by: Chris Stehno ]

- Chris Stehno, SCPJ
Madhavi Gupta

Joined: Jan 30, 2002
Posts: 5
Hi Guys,
Thank you very much for your replies.
The problem was with mm.
I agree. Here's the link:
subject: Formatting Dates
jQuery in Action, 3rd edition