This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# BigDecimal to Date Conversion

Sanjeev Dubey
Greenhorn
Posts: 16
I want to convert a a date in BigDecimal to Date

BigDecimal date = new BigDecimal(20080221);

to
Date date= 21-Feb-08 ( with DD-MMM-YY format)

Can any one help?

Sanjeev Dubey
Greenhorn
Posts: 16
public static java.sql.Date dateToDB(BigDecimal dateFrom){
if ( dateFrom == null )
return null;
String dateStr = dateFrom.toString();
String year = dateStr.substring(0,4);
String month = dateStr.substring(4,6);
String day = dateStr.substring(6,8);
calendar.set(Calendar.YEAR, Integer.parseInt(year));
calendar.set(Calendar.MONTH,Integer.parseInt(month)-1);
calendar.set(Calendar.DAY_OF_MONTH,Integer.parseInt(day));
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
java.sql.Date date = new java.sql.Date(calendar.getTimeInMillis());
return date;
}

Campbell Ritchie
Sheriff
Posts: 50702
83
Far better to use the mod and divide operations.

And why would you want an integer in a BigDecimal in the first place?

Rob Spoor
Sheriff
Posts: 20709
68
The most robust solution is to use the existing library:

Keep in mind though, that a Date object has no real formatting. It represents a moment in time. Sure you see a date when you call its toString() method, but that's not the Date's actual format - it has none. Use (Simple)DateFormat to convert it into a formatted string.