0

Get time of a particular timezone and check whether the current time lies between 12:00 am and 5:45 am. If the time is between 12 &5:45 need to execute some statements and else another statement

  • Search for JobScheduller on Android. e.g. https://medium.com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129 – Iogui Nov 01 '20 at 06:15

1 Answers1

0

Set timeZone as needed

public class demo {
    public static void main(String[] args) throws ParseException {
        String timeZone = "GMT+5:30";//Set needed timezone
        java.util.TimeZone tz = java.util.TimeZone.getTimeZone(timeZone);
        String dd = Integer.toString(Calendar.getInstance(tz).get(Calendar.DATE));
        String M = Integer.toString(Calendar.getInstance(tz).get(Calendar.MONTH));
        String yyyy = Integer.toString(Calendar.getInstance(tz).get(Calendar.YEAR));
        String dateString = dd + "-" + M + "-" + yyyy; /* Doing this because current
        date at a given timezone can be different from your date*/
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
        String lowerLimit = dateString + " 00:00:00";//Given Upper and lower limits
        String upperLimit = dateString + " 05:45:00";

        //required upper and lower limits and current time in milliseconds
        long timeLower = simpleDateFormat.parse(lowerLimit).getTime();
        long timeUpper = simpleDateFormat.parse(upperLimit).getTime();
        long currentTimeInMillis = Calendar.getInstance(tz).getTimeInMillis();

        if ((timeLower < currentTimeInMillis) && (currentTimeInMillis < timeUpper)) {
            System.out.println("execute true statements here");
        } else {
            System.out.println("execute false statements here");
        }
    }
}
  • Consider not using `TimeZone`, `Calendar` and `SimpleDateFormat`. Those classes are poorly designed and long outdated, the last in particular notoriously troublesome. Instead use `LocalTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Nov 01 '20 at 20:22