Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Formatting Dates

 
Madhavi Gupta
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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));
System.out.println(dt.toString());
Calendar calendar = new GregorianCalendar();
calendar.setTime(dt);
int month = calendar.get(Calendar.MONTH) + 1;

Thanks in advance,
Madhu
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mm is for minutes.
MM is for month.
 
Chris Stehno
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay... so you want the date to look like:
02/25/2002
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 ]
 
Madhavi Gupta
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,
Thank you very much for your replies.
The problem was with mm.
Madhu
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic