import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static long findClosestMidnight(long microsecondsSinceEpoch, String timeZone) {
        // Convert microseconds to milliseconds
        long millisecondsSinceEpoch = microsecondsSinceEpoch / 1000;

        // Create an Instant from the milliseconds
        Instant instant = Instant.ofEpochMilli(millisecondsSinceEpoch);

        // Create a ZonedDateTime in the specified time zone
        ZoneId zoneId = ZoneId.of(timeZone);
        ZonedDateTime zonedDateTime = instant.atZone(zoneId);

        // Get the current date in the specified time zone
        LocalDate currentDate = zonedDateTime.toLocalDate();

        // Find the midnight before and after the current time
        ZonedDateTime midnightBefore = currentDate.atStartOfDay(zoneId);
        ZonedDateTime midnightAfter = midnightBefore.plusDays(1);

        // Calculate the difference between the current time and each midnight
        long diffBefore = Math.abs(zonedDateTime.toEpochSecond() - midnightBefore.toEpochSecond());
        long diffAfter = Math.abs(zonedDateTime.toEpochSecond() - midnightAfter.toEpochSecond());

        // Find the closest midnight
        ZonedDateTime closestMidnight = (diffBefore <= diffAfter) ? midnightBefore : midnightAfter;

        // Convert the closest midnight back to microseconds since epoch
        long closestMidnightMicroseconds = closestMidnight.toInstant().toEpochMilli() * 1000;

        return closestMidnightMicroseconds;
    }

    public static void main(String[] args) {
        long microsecondsSinceEpoch = 1659454812345678L; // Example input
        String timeZone = "America/New_York"; // Example time zone

        long closestMidnight = findClosestMidnight(microsecondsSinceEpoch, timeZone);
        System.out.println("Closest Midnight in Microseconds: " + closestMidnight);
    }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: