• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Get the month from java.util.Date

 
Marty Das
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a date of type java.util.Date and I need to read(get) the month from this date...like 0,1,2..so on.
Any help appreciated.
 
Kevin Mukhar
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by jman bony:
I have a date of type java.util.Date and I need to read(get) the month from this date...like 0,1,2..so on.
Any help appreciated.

RTFJ - Read The Fine Javadoc
Javadoc for Date shows a getMonth() method, but says it's deprecated, use Calendar.get(Calendar.Month).
Going to the Javadoc for Calendar, you will find two constructors, but neither takes a Date object. But there must be some way to set the time for a calendar. Scroll down the method list and you will find setTime(Date) method.
With that information, you should be able to figure out this code:
Calendar cal = new Calendar();
cal.setTime(myDate);
int month = cal.get(Calendar.MONTH);
This int value corresponds to the various contstants in Calendar: Calendar.JANUARY, Cealendar.FEBRUARY, etc.
Also, if you had mucked about with the Javadoc, you might have run across a GregorianCalendar class. The Javadoc for GregorianCalendar has essentially the same code shown above.
Another good source for basic "How do I..." questions is the Java FAQ at http://www.afu.com/intro.html
 
Marty Das
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kevin,
I get this error if I use your code:
java.util.Calendar is abstract; cannot be instantiated
Calendar cal = new Calendar();
 
Marty Das
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorryyyy..
I figured it out...
I should use it like so
java.util.Calendar cal = java.util.Calendar.getInstance();
and then cal.set .....etc
Thanks a ton
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic