programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Working with Date and Time

Greenhorn
Posts: 7
Hi,

I've written the following code to calculate the elapsed time since birth. But on running it, the month and year are not getting displayed correctly. I'm getting a negative value for the month and also the elapsed year is wrong. Please help me...

Thanks,
Babu Rajendran

Bartender
Posts: 10336
Can you explain what this calculation does? :

System.out.println("\t" + elapsedMS / (12 * 30 * 24 * 60 * 60 * 1000) + " years");

Specifically, what are you trying to achieve with the 30?

Also, remember that any literal integers in your program will be treated as int values, and that ints have a maximum size. Try these two lines to watch what happens when you exceed this maximum:

(the l in the above is a lowecase letter 'L')
[ April 23, 2007: Message edited by: Paul Sturrock ]

Help Me
Greenhorn
Posts: 7
I'm just converting from milliseconds to years. Well..I got the point now. Thanks a lot!

Regards,
Babu Rajendran

Paul Sturrock
Bartender
Posts: 10336

Originally posted by Babu Rajendran:
I'm just converting from milliseconds to years. Well..I got the point now. Thanks a lot!

Regards,
Babu Rajendran

Are you sure your logic is correct?

Java Cowboy
Sheriff
Posts: 16078
88

Originally posted by Babu Rajendran:
I'm just converting from milliseconds to years.

A year is not 12 * 30 = 360 days.

(instanceof Sidekick)
Ranch Hand
Posts: 8791
Computing duration with months in it from milliseconds is suspect, I think. Start from January 31 of any year, what answers would you want from each of the following?

jan31 + oneMonth = ??
jan31 + oneMonth + oneMonth = ??
jan31 + twoMonths = ??
jan31 + oneMonth - oneMonth = ??

Years might bother some folks, too. What's

feb29 + oneYear?
feb29 + oneYear - oneYear?

I think you can get the answers humans expect for the difference between dates by breaking up the year, month, day parts of the date and working from there. What do you think?

 Consider Paul's rocket mass heater.