Get only time in milliseconds in android

I want to check if current time is 00:01AM then do a particular job for that I am trying convert only the time to milliseconds when I do that the I get different milliseconds value for different dates.

I tried this:

Calendar cal = Calendar.getInstance();

cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(getResources().getString(R.string.zerozero)));
cal.set(Calendar.MINUTE, Integer.parseInt(getResources().getString(R.string.one)));
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);


long alarmtime = cal.getTimeInMillis();
long currenttime = System.currentTimeMillis();

Log.e("Value", "= " + alarmtime + " " + currenttime);

When I do the above: milliseconds for today: it shows 1458066660000 and for tomorrow it is :1458153060000

So how to check if current time is 00:01AM or not?

Easy way how to compare current Time with given time..?

Thanks!

Jon Skeet
people
quotationmark

I don't believe there's a calendar field for "millisecond of day", but you could use:

long millisecondOfDay = 
    TimeUnit.HOURS.toMillis(cal.get(Calendar.HOUR_OF_DAY)) +
    TimeUnit.MINUTES.toMillis(cal.get(Calendar.MINUTE)) +
    TimeUnit.SECONDS.toMillis(cal.get(Calendar.SECOND)) +
    cal.get(Calendar.MILLISECOND);

To get the current time-of-day you could then use:

cal.setTimeInMillis(System.currentTimeMillis());

... and then perform the same calculation.

All of this is sensitive to the time zone of the calendar of course, so make sure that's appropriate.

As noted in comments, if you just want to find if it's 00:01, you only need to find the minute of day:

int minuteOfDay = 
    TimeUnit.HOURS.toMinutes(cal.get(Calendar.HOUR_OF_DAY)) +
    cal.get(Calendar.MINUTE);

Or just check those two fields for equality:

if (cal.get(Calendar.HOUR_OF_DAY) == 0 &&
    cal.get(Calendar.MINUTE) == 1)
{
    ...
}

But if this is for an alarm, you may well be better off working out the next occurrence and storing that, then checking whether that time has already passed or not. It's hard to know exactly what to advise without a lot more context, but hopefully this has given you enough tools to do the rest yourself...

people

See more on this question at Stackoverflow