Search code examples
javascriptjquerytimetimercountdown

How can I set a timer to end at 12pm PST every day?


I want to create a countdown on my page that ends at a certain every day. There is a shipping deadline for purchases and we want to show how much time is remaining. So there needs to be an if statement to see if it's past that time and not show the counter and instead show a 'order will ship tomorrow' div.

I've found this great javascript countdown by Keith Wood.

And I was playing with this code from another SO post

But since it's a shipping deadline it needs to be exact, and I'm afraid that code only deals with the browser's local time. I need it to be set to 12pm Pacific time.


Solution

  • You could get the time from your server and parse it in JavaScript. If you're using PHP you could do something like this:

    var serverTime = Date.parse('<?= date("r"); ?>');
    

    This will let PHP echo an RFC2822 formatted date and JavaScript will parse it and return a Date object. From here you can continue with the other solutions you have.

    I haven't tested this but the key is to get the time from your server and parse it in JavaScript (if the server isn't in the correct time zone you can just adjust the time).

    Update: Handling timezones.

    To take timezones into account you could use the DateTime object in PHP like this:

    $datetime = new DateTime();
    $datetime->setTimezone('Pacific/Nauru');
    

    and then echo it to your JavaScript like this:

    var serverTime = Date.parse('<?= $datetime->format("r"); ?>');
    

    Again, I haven't tested this but this is what I would do.

    Documentation for Date.parse

    PHP date() function

    DateTime object