How do I know if it’s past midnight or a new day has begun?

Asked

Viewed 197 times

0

I need to make a make a if for when past midnight, but how can I get this information even with mobile turned off?

I’m trying like this these days:

date_current = simpleDateFormat.parse(strDate);
if (date_current.getTime() == 0){
    dados.setmeianoite(true);
}

However if it passes the midnight while the mobile is in the background or turned off it does not fall on if, consequently does not do what I want.

What I need to know is if he turned midnight and it’s not midnight.

  • 1

    Running this in a Service to run something in the background? https://developer.android.com/guide/components/services.html

  • Yes, I’m running a service

  • 3

    Look, to run a program with your phone turned off, just making a pact with the devil.

  • This question smells like XY problem - I guess you don’t have to give one setmeianoite(true);, and see what is the last date something happened and compare it with the current date, if they are on different days.

2 answers

2


date_current.getTime() == 0 will only return true when midnight of the day January 1, 1970 (epoch).

The simplest way to check the hours is by using a Calendar.

date_current = simpleDateFormat.parse(strDate);

Calendar calendar = Calendar.getInstance();
calendar.setTime(date_current);

if(calendar.get(Calendar.HOUR_OF_DAY) == 0) {
  dados.setmeianoite(true);
}
  • I did more or less this, but also added a check on the device boot, because this way, if that time turns when the phone is off, it does not true arrow.

2

I do not know very well Java or Android, but I believe it is a matter of algorithm here.

To begin with, see the response of Leonardo Lima. Your program compares the current time date with a specific date, not midnight of the day you are on.

But one more thing remains. Your program runs from time to time, right? What I suggest:

  • Each time the relevant excerpt is executed, store in your application data the date-time when the excerpt was executed.
  • Still in this section, compare the current date with the date of the last time the program was executed.

You don’t have to take the time into consideration. If the current date and last execution date are different, then the day "turned" since the last time the program ran.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.