Date comparisons

L

laredotornado

Hi,

I'm using Java 1.5. I have a java.util.Date object and I would like
to determine if it's date (i.e. year, month, and day) are greater than
(in the future) or equal to today's date (year, month, and day).
However, I don't care about any time component (hour, minute,
second ...) when the comparison is taking place. What is the easiest
way I can determine this?

Thanks, - Dave
 
L

laredotornado

If you are in the UTC time zone (often called GMT too), then this
is simple. Use this:

        public static int dayCount(Date d)
        {
                return (int)(d.getTime() / 86400000L);
        }

which returns the date as an integral count of days since January 1st,
1970. You then just have to compare those day counts.

For other time zones, you will have to resort to Calendar and
TimeZone. Create a TimeZone instance for your time zone, then get
a Calendar instance (with Calendar.getInstance(TimeZone)), and use
it to convert your dates into years, months and days.

        --Thomas Pornin

Thanks. This is just the simple solution I was looking for. One
follow up . Why is the timezone important? If I know that both my
Date objects are the same time zone, wouldn't it still work even if
that time zone weren't GMT? - Dave
 
N

Nigel Wade

Thanks. This is just the simple solution I was looking for. One follow
up . Why is the timezone important? If I know that both my Date objects
are the same time zone, wouldn't it still work even if that time zone
weren't GMT? - Dave

Because wall clock time (and this includes "what day is it" type
questions) in one timezone is different from wall clock time in another
timezone.

Consider the two instants in time 1 minute before midnight GMT and 1
minute after midnight GMT. They belong to different days in London, but
are both in the same day in New York (or any other timezone for that
matter). Your two Dates are in GMT, but you may well not be. Asking "what
day do these Dates represent" depends on what timezone you are in when
you ask the question.

Timezones are important. Ignore them at your peril.
 
R

Roedy Green

I'm using Java 1.5. I have a java.util.Date object and I would like
to determine if it's date (i.e. year, month, and day) are greater than
(in the future) or equal to today's date (year, month, and day).
However, I don't care about any time component (hour, minute,
second ...) when the comparison is taking place. What is the easiest
way I can determine this?

1. use BigDate. see http://mindprod.com/products1.html#BIGDATE

2. extract the long timestamp from each date. Divide by the number of
milliseconds in a day to get days since 1970. Compare those, keeping
in mind these are UTC days. Christmas in Moscow may compare different
from Christmas in Toledo.

for background see http://mindprod.com/jgloss/calendar.html
http://mindprod.com/jgloss/time.html
http://mindprod.com/jgloss/date.html
--
Roedy Green Canadian Mind Products
http://mindprod.com

The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.
~ Tom Cargill
 
L

Lew

Hi,

I'm using Java 1.5.  I have a java.util.Date object and I would like
to determine if it's date (i.e. year, month, and day) are greater than
(in the future) or equal to today's date (year, month, and day).
However, I don't care about any time component (hour, minute,
second ...) when the comparison is taking place.  What is the easiest
way I can determine this?

Use Calendar. Normalize to the same time zone. Zero out the time
portion (using 'set()', *not* 'clear()'!). Compare using 'after()' or
'before()'. Read the Javadocs.
 
L

Lew

Roedy said:
2. extract the long timestamp from each date.  Divide by the number of
milliseconds in a day to get days since 1970. Compare those, keeping
in mind these are UTC days. Christmas in Moscow may compare different
from Christmas in Toledo.

That will have troubles this weekend in my part of the world, i.e.,
give the wrong answer.

The number of milliseconds in a day depends on the date.
 
R

Roedy Green

That will have troubles this weekend in my part of the world, i.e.,
give the wrong answer.

The number of milliseconds in a day depends on the date.

I have long railed against DST as a nutty idea.
http://mindprod.com/jgloss/dst.html

The Rachael Maddow show trashed it tonight. It turns out it does not
save energy. With the extra evening hours people drive to the mall or
ballpark. It is a retail stimulus and a way to increase gas
consumption.

The story is we do it for the farmers. They strenuously opposed it
when it was introduced. It gave them one less hour before the city
markets opened.

I wonder how many people have been killed by the anomalies when the
time changes. I could imagine some incompetent maker of medical pumps
giving a double dose, or skipping a dose.

I think anyone who has to co-ordinate should be tracking time in UTC.
But even then data entry still happens in local time.
--
Roedy Green Canadian Mind Products
http://mindprod.com

The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.
~ Tom Cargill
 
R

Roedy Green


BigDate from = new BigDate( 2010, 2, 28);
BigDate to = new BigDate ( 2010, 3, 12 );
int diff = to.compareTo( from );

Or starting with a timestamp in the form of a UTC Date and a TimeZone

BigDate from = new BigDate( dateFrom, tzFrom );
BigDate to = new BigDate ( dateTo, tzTo );
int diff = to.compareTo( from );
--
Roedy Green Canadian Mind Products
http://mindprod.com

The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.
~ Tom Cargill
 
L

Lew

Roedy said:
I have long railed against DST as a nutty idea.
http://mindprod.com/jgloss/dst.html ....
The story is we do it for the farmers. They strenuously opposed it
when it was introduced. It gave them one less hour before the city
markets opened.

I wonder where that canard originated. It's so patently untrue. As if the
cows would change when they need to be milked! Farmers work without regard
for clocks, unless you count sundials.

The original origin of Daylight Savings (I refuse to use the correct "Daylight
Saving") was to eke an extra hour of work out of factory workers without
having to pay for lighting. This was in the days before architecture changed
and made cooling much more expensive than lighting.

You are correct that people die or get injured in the spring-forward time
change. I've read that it has something to do with losing an hour's sleep
that weekend (this coming weekend, here).

DST was the source of a bug in a J2EE system I worked on a couple of years
ago. The code calculated whether a customer was more than seven days late
with a form using the naive calculation of so many seconds per day, and local
time. Tsk, tsk.
 
G

George Neuner

The original origin of Daylight Savings (I refuse to use the correct "Daylight
Saving") was to eke an extra hour of work out of factory workers without
having to pay for lighting. This was in the days before architecture changed
and made cooling much more expensive than lighting.

Undoubtedly it quickly evolved into a business issue, but I thought
the original use was wartime fuel conservation. AFAIK, WWI Germany
was the first country to use daylight saving - to save coal.

George
 
A

Arved Sandstrom

laredotornado said:
Thanks. This is just the simple solution I was looking for. One
follow up . Why is the timezone important? If I know that both my
Date objects are the same time zone, wouldn't it still work even if
that time zone weren't GMT? - Dave

The actual timezone _isn't_ important, not in the sense that you mean.
All you need for *any* timezone TZ is a calculation method X that gives
you integral days for a date, from an epoch. It just so happens that for
GMT the calculation method X is quite simple, as Thomas points out - for
the others you resort to the APIs.

AHS
 
L

Lew

George said:
Undoubtedly it quickly evolved into a business issue, but I thought
the original use was wartime fuel conservation. AFAIK, WWI Germany
was the first country to use daylight saving - to save coal.

You're right, but that is saying the same thing. I didn't say "business" or
"peacetime" factory workers.

How did it save coal for Germany? They may have claimed that was the reason,
but what savings could there have been? It took the same amount of coal to
make steel in daytime or nighttime - the only difference would have been to
provide lighting back in those days.
 
G

George Neuner

You're right, but that is saying the same thing. I didn't say "business" or
"peacetime" factory workers.

How did it save coal for Germany? They may have claimed that was the reason,
but what savings could there have been? It took the same amount of coal to
make steel in daytime or nighttime - the only difference would have been to
provide lighting back in those days.

I can only speculate because what I have read and seen in television
documentaries has been short on specifics.

At the time Germany was the world's leader in making coal derivatives:
synthetic machine fuels and oils, gas for lighting and heating,
chemicals (including explosives and medicines), pigments, dies, etc.
Much of the economy revolved around coal in one way or another - it
wasn't just used for making steel.

In 1915, many German cities and towns were lit and heated by coal gas.
Whether lighting was by coal gas or electric generated by burning
coal, either way extended afternoon daylight would cut into that use.
Also a good part of Germany is mountainous so it may have had some
impact on heating as well in the Spring and Fall - the sun shines the
same amount regardless of the clock, but time does seem to affect when
people feel cold.

Germany was rather late in abandoning general use of coal fuels -
because they had lots of coal but little oil or natural gas of their
own. Following WWI, much of Germany's industry was dismantled - at
the start of WWII, most of the coal related industries were gone and
fossil oil had become the main fuel.

Hitler tried to revive coal fuel production when Germany's oil
reserves were dwindling. After taking Poland, France and
Checkoslovakia, Germany had coal reserves coming out of its ears but
it didn't have a great deal of oil until invading Georgia (and they
never got much benefit from the Georgian fields due to sabotage).

George
 
D

Dr J R Stockton

In comp.lang.java.programmer message <[email protected].
If you are in the UTC time zone (often called GMT too), then this
is simple.

As I recall, only the ISS, Iceland, and a few countries around Liberia
use GMT year-round. The corresponding time zone is considerably larger,
including the British Isles and Portugal. Time Zones do not routinely
change in Spring and Autumn.


In comp.lang.java.programmer message <[email protected]>,
Consider the two instants in time 1 minute before midnight GMT and 1
minute after midnight GMT. They belong to different days in London, but
are both in the same day in New York (or any other timezone for that
matter).

They are not different days in Summer in the British Isles.
They are different days in Summer in lands in the next zone West (small
Atlantic islands).



In comp.lang.java.programmer message <9ahmp5de690kdeodkvdjenjncv78l0tlt1
@4ax.com>, Sat, 13 Mar 2010 03:01:10, George Neuner
Undoubtedly it quickly evolved into a business issue, but I thought
the original use was wartime fuel conservation. AFAIK, WWI Germany
was the first country to use daylight saving - to save coal.

But not the first nationality. British first used it on 1915-09-26,
Germany not till the end of the following April. Sundry Canadian
localities used it in the preceding decade.
 
A

Arne Vajhøj

I'm using Java 1.5. I have a java.util.Date object and I would like
to determine if it's date (i.e. year, month, and day) are greater than
(in the future) or equal to today's date (year, month, and day).
However, I don't care about any time component (hour, minute,
second ...) when the comparison is taking place. What is the easiest
way I can determine this?

There must be several ways.

My suggestion:

public static boolean isFutureDay(Date d) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
Calendar fut = Calendar.getInstance();
fut.add(Calendar.DATE, 1);
fut.set(Calendar.HOUR_OF_DAY, 0);
fut.set(Calendar.MINUTE, 0);
fut.set(Calendar.SECOND, 0);
fut.set(Calendar.MILLISECOND, 0);
return cal.compareTo(fut) >= 0;
}

Arne
 
N

Nigel Wade

In comp.lang.java.programmer message <[email protected]>,


They are not different days in Summer in the British Isles. They are
different days in Summer in lands in the next zone West (small Atlantic
islands).

Then London would be in BST, not GMT, and under the inclusion of "any
other timezone".
 
R

RedGrittyBrick

Then London would be in BST, not GMT, and under the inclusion of "any
other timezone".

IIRC Dr John Stockton has previously pointed out that BST is not a timezone.

Perhaps because of the terminology used in Unix, I have previously
conflated the ideas of clock shifts such as summer time (or DST) with
the geographic regions known as time-zones.
 
D

Dr J R Stockton

In comp.lang.java.programmer message said:
Then London would be in BST, not GMT, and under the inclusion of "any
other timezone".

The marking of a time with GMT or UTC does not mean that the local time
is GMT or UTC. Listen to the BBC World Service at midnights after
2010-03-28T12:00.

Without a change in rules, London is in the "GMT" time zone all year
round. Time zones do not move seasonally. Time Zone gives Winter Time,
and there is an additional offset in many temperate regions, of a half
or one hour, in the Summer half of the year.

Do not confuse time zone with civil time offset; that is a habit
invented by ill-educated Americans, probably in California.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top