4

I have a scheduler that needs to check if the incoming timestamp is current day's timestamp.

The incoming timestamp will be of the format Eg:1384956395.

How to check this in java? Please help. I am not using Joda

Poppy
  • 2,902
  • 14
  • 51
  • 75

2 Answers2

8

The epoch you posted is in seconds. Java uses milliseconds so you have to convert it and then compare the two.

long epochInMillis = epoch * 1000;
Calendar now = Calendar.getInstance();
Calendar timeToCheck = Calendar.getInstance();
timeToCheck.setTimeInMillis(epochInMillis);

if(now.get(Calendar.YEAR) == timeToCheck.get(Calendar.YEAR)) {
    if(now.get(Calendar.DAY_OF_YEAR) == timeToCheck.get(Calendar.DAY_OF_YEAR)) {
    }
}

You can also change the time zone if you do not want to use the default, in case the input epoch is in a different time zone.

Dodd10x
  • 3,344
  • 1
  • 18
  • 27
  • Works for me, tnx! I appreciate answers with working code like that easy to test and to import! [btw, you miss a ")" on second if ;)] – Andrea Girardi Aug 15 '14 at 13:23
0

Assuming that your timestamp was created via System.currentTimeMillis() (or any other compatible mechanism), you can do the following:

  1. Create a Calendar instances and set the hour, minute, second and millisecond fields to zero. This is today at 0:00:00,0.

  2. Clone the instance and add 1 day. You'll get tomorrow at 0:00:00,0.

  3. Now check if your timestamp is in the range between today.getTime() (inclusive) and tomorrow.getTime() (exclusive).

isnot2bad
  • 24,105
  • 2
  • 29
  • 50