0

I've written a Java function getRemainingTime(Date currentDate, Date expirationDate) that calculates the difference between two dates and returns the result in a user-friendly format. The main purpose is to send notifications to users about the time remaining until a certain event. The notification needs to be sent from 12 to 12 hours and the notification message should be like this:

'You have left 6 days and 12', after the next 12 hours the notification will be sent again and the message should be like this 'You have left 6 days', and so on. In this case the expiration date is 7 days + from the moment of a certain event in my app.

This is my function:

public static String getRemainingTime(Date currentDate, Date expirationDate) {

        // Calculate the time difference in milliseconds between the two dates
        long diff = expirationDate.getTime() - currentDate.getTime();

        long days = TimeUnit.MILLISECONDS.toDays(diff);
        long remainingMillisAfterDays = diff - TimeUnit.DAYS.toMillis(days);

        long hours = TimeUnit.MILLISECONDS.toHours(remainingMillisAfterDays);
        long remainingMillisAfterHours = remainingMillisAfterDays - TimeUnit.HOURS.toMillis(hours);

        long minutes = TimeUnit.MILLISECONDS.toMinutes(remainingMillisAfterHours);

        // Check and apply rounding if the time is close to the next day or hour
        if (hours == 23 && minutes >= 30) {
            days++;
            hours = 0;
            minutes = 0;
        }

        // Return the remaining time based on the calculated days, hours, and minutes
        if (days > 0 && (hours >= 12 || (hours == 11 && minutes >= 30))) {
            return days + " days and 12 hours";
        } else if (days > 0) {
            return days + " days";
        } else if (hours >= 11 || (hours == 10 && minutes >= 30)) {
            return "12 hours";
        } else {
            return "less than one hour";
        }
    }

The function approximates values for better user comprehension. For instance:
• 11 hours and 30 minutes is rounded to 12 hours.
• 23 hours and 30 minutes is rounded to 1 day.

My requirements are:
1. The notification should display the time remaining in days and hours.
2. Near values (e.g., 11 hours 30 minutes) should be approximated for better user understanding.
3. I'm planning to trigger these notifications based on the return value of this function. For instance, if the function returns "12 hours", the user should get a notification saying "12 hours have passed."

Any suggestions or improvements are greatly appreciated. Thank you!

0 Answers0