retrieve dates at the correct time irrespective of the dst

Use LocalTime

Check the following introduction of LocalTime:

This class is useful for representing human-based time of day, such as movie times, or the opening and closing times of the local library.

A date-time with timezone or zone-offset is the wrong choice for this use case. I am assuming that you have the users’ timezone in your database and you have scheduled some corn job to send the notification. When the job runs to send the notification, simply check which users have a local time of 7:00 am (plus/minus a few minutes e.g. 5 minutes as per your requirement and frequency of the corn job) at that time e.g.

import java.time.LocalTime;
import java.time.ZoneId;

public class Main {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now(ZoneId.of("Europe/London"));// Your server's timezone
        System.out.println(isLocalTimeSameAsNotificationTime(ZoneId.of("Asia/Calcutta"), time)); // User's timezone
    }

    static boolean isLocalTimeSameAsNotificationTime(ZoneId zone, LocalTime notificationTime) {
        LocalTime time = LocalTime.now(zone);// Local time at the param zone

        // True if +/- 5 minutes notificationTime
        return !(time.isBefore(notificationTime.minusMinutes(5)) || time.isAfter(notificationTime.plusMinutes(5)));
    }
}

The query in the corn job should be something like SELECT userId, user FROM tableName WHERE notificationTime = now plus/minus 5 minutes and now you have to loop through this resultset. For each record in the resultset, you need to call the function, isLocalTimeSameAsNotificationTime passing the timezone and server’s local time as params and trigger the notification if it returns true.

Note: The SQL query I have mentioned here is for an example of how you have to write the query; it’s not syntactically correct.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top