Problem constructing java.util.Date object

dsmclaughlin
dsmclaughlin used Ask the Experts™
on
Hi,

I'm trying to construct a java.util.Date object to be a date very far in the future but I'm having problems.

To construct the date 01/01/3000 I tried the following:

new Date (86400 * 365 * 1030)

that is, the number of seconds in a day * the number of days in a year * the number of years (3000 - 1970 = 1030) but this gives me the date 21/10/1969. I thought that the Date constructor allowed you to construct a date by supplying the number of milliseconds elapsed since 01/01/1970 but this doesn't seem to work. Can anyone help?

Many thanks

~drew

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Try the following.
Calencar c = Calendar.getInstance();
c.set(Calendar.YEAR, 3000);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DAY_OF_MONTH, 1);
 
Date d = c.getTime();

Open in new window

Where you read Calencar, that should be Calendar.
Top Expert 2016

Commented:
Easier would be


Date d = new GregorianCalendar(3000, 1, 1).getTime();

Open in new window

HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Top Expert 2016

Commented:
This might give you a clue as to your error: instead of

>>new Date (86400 * 365 * 1030)

try
new Date (86400L * 365 * 1030) 

Open in new window

Top Expert 2016
Commented:
Plus you have a typo:

>>new Date (86400L * 365 * 1030)

should be
new Date (86400000L * 365 * 1030)

Open in new window

Top Expert 2016

Commented:
(So best to try my 2nd correction first - it will show you that the real reason for the error lies in the issues around my first correction)

Author

Commented:
@ CEHJ why is 86400 a typo other than for the fact I left the L off to make it a long? Google tells me that there are 86400 seconds in a day....I'm slightly confused.
Top Expert 2016

Commented:
Date works on *milliseconds* not seconds

Author

Commented:
ahhhh good man! cheers! :)
Top Expert 2016

Commented:
You might be surprised to find that the latest date that can be constructed using int is

Sun Jan 25 21:31:23 GMT 1970

;-)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial