Kiarash
Kiarash

Reputation: 7998

Java Date object shows time in the future

I'm making a new date object some time before current time. If I have it to show 1 day before today, it works fine. but if I want to show 30 days ago, it goes to future (?)

Date date = new Date();
long sometime = 24 * 60 * 60 * 1000; //a day
System.out.println(date.getTime() );
Date sometimeago = new Date(date.getTime() - sometime);
System.out.println(sometimeago );
sometime = 30* 24 * 60 * 60 * 1000; //a month
sometimeago = new Date(date.getTime() - sometime);
System.out.println(sometimeago );

Output:

1408160853776
Thu Aug 14 20:47:33 PDT 2014
Thu Sep 04 13:50:21 PDT 2014

What's limiting here? Reaching Long limit?

Upvotes: 2

Views: 2057

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338181

tl;dr

LocalDate.now()
         .minusDays( 1 ) 

java.time

The modern java.time classes provide these functions.

If I have it to show 1 day before today,

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
LocalDate yesterday = today.minusDays( 1 ) ;

I want to show 30 days ago

LocalDate thirtyDaysAgo = today.minusDays( 30 ) ;

Or perhaps you want a logical month rather than literally thirty days.

LocalDate monthAgo = today.minusMonths( 1 ) ;

Perhaps you want a date-time rather than a date-only value.

ZonedDateTime now = ZonedDateTime.now( z ) ;
ZonedDateTime zdtYesterday = now.minusDays( 1 ) ;
ZonedDateTime zdtThirtyDaysAgo = now.minusDays( 30 ) ;
ZonedDateTime zdtMonthAgo = now.minusMonths( 1 ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240860

integer overflow in int literals,

in your case int literals gets evaluted before and that results in negative result and than gets assigned to long

sometime = 30* 24 * 60 * 60 * 1000; //a month 

this results in -1702967296

convert it to

sometime = 30* 24 * 60 * 60 * 1000L; //a month 

note: L to make it long literal and then multiply

Better to use Calendar class for Date manipulation


Also See

Upvotes: 5

Related Questions