How to check a date (in UTC format) is 48 hours before today date

I tried to convert the new today's date object to UTC. But no luck since new date object is always in local time zone. I have been trying to verify two dates using 'before' method. date1 is in UTC format. date2 is today.

The below code always prints the today's date object in local time zone.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        String todayStr = sdf.format(new Date());// This string is in UTC. But I need date object in UTC.

        try {
            System.out.println(sdf.parse(todayStr));// This is still printing in local time zone.
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }


    }

}
Jon Skeet
people
quotationmark

A Date object isn't in any time zone - it's just a wrapper around the number of milliseconds since the Unix epoch. The Unix epoch is typically described in terms of UTC (namely midnight at the start of January 1st 1970) but it's really just a point in time.

To get the point in time 48 hours before "now", you can use something like:

Date earlier = new Date(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(48));

You can compare that with any Date object to see which occurred earlier in time - again, with no reference to any particular time zone.

(This isn't an easily testable solution, admittedly - I prefer to abstract System.currentTimeMillis() behind a Clock interface, so that I can test with a fake clock set to whatever time I want.)

Unless you need a string representation, ignore it - as soon as you want a string representation, you need to think about both which calendar system and time zone you're interested in.

Note that you talk about "today's date" in the question - if you mean the start of a particular day, then the time zone is relevant, and you'll need to do more work.

Finally, I'd suggest that if you possibly can, you use either java.time.* from Java 8, or Joda Time instead of java.util.Date etc. The first two are both much better APIs than the last.

The below code always prints the today's date object in local time zone.

Yes, that's because Date.toString() uses the local time zone. That's just what it (unfortunately) does, and it doesn't mean that the Date object is "in" the local time zone.

people

See more on this question at Stackoverflow