Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to convert 4 strings MMDDCCYY to a date object?

 
Reed Peters
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am accessing an old database via SQL. The database stores dates in four different fields-Month, Day, Century, and Year- each are two digits. What is the best approach to use to convert these into a Date object? Also, I noticed that I am not getting the leading zeros either, so july would be a 7 instead of 07.
Thanks in advance.
[ October 25, 2002: Message edited by: Reed Peters ]
 
San Su
Ranch Hand
Posts: 313
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Calendar cal = Calendar.getInstance().
cal.set(Calendar.DATE, nDate);
cal.set(Calendar.MONTH, nMonth);
cal.set(Calendar.YEAR, nCentury + nYear);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Does this help? Sorry it is a quick response. Forgive me if it doesnt work. There are several other approaches.
[ October 25, 2002: Message edited by: Sankar Subbiah ]
 
Reed Peters
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Sankar. That worked great.
 
yi zhu
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also month begins with 0
 
Jamie Robertson
Ranch Hand
Posts: 1879
MySQL Database Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use SimpleDateFormat to parse Strings to Dates, depending on their String pattern:
 
Jamie Robertson
Ranch Hand
Posts: 1879
MySQL Database Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, just beware of this hidden detail:

Month Mappings
mon -> int -> Calendar field
Jan -> 0 -> Calendar.JANUARY
Feb -> 1 -> Calendar.FEBRUARY
Mar -> 2 -> Calendar.MARCH
...
Dec -> 11 -> Calendar.DECEMBER

Just a heads up on this, I know it caused me unforseen problems before!
Jamie
[I think that is what Yi briefly implied]
[ October 29, 2002: Message edited by: Jamie Robertson ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic