Can someone show me how to create a JavaScript countdown with a Unix timestamp?

I'm in the process of building a website that requires a countdown to a specific time, but I'm struggling to find a solution that allows me to input a Unix timestamp and display the same countdown for all users, irrespective of their time zones.

I've come across various options involving jQuery and other libraries, but I'd prefer not to rely on any external libraries unless it's absolutely necessary.

Here's what I experimented with:

const countdownTimer = setInterval(() => {
    const countDownTime = new Date("Mar 1 2024 11:00:00").getTime();
    const currentTime = new Date().getTime();
    const timeLeft = countDownTime - currentTime;

    const daysLeft = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
    const hoursLeft = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutesLeft = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
    const secondsLeft = Math.floor((timeLeft % (1000 * 60)) / 1000);

    if (timeLeft < 0) {
        clearInterval(countdownTimer);
        document.getElementsByClassName("countdown")[0].innerHTML = "Released!";
    } else {
        document.getElementsByClassName(
            "countdown"
        )[0].innerText = `${daysLeft}d ${hoursLeft}h ${minutesLeft}m ${secondsLeft}s`;
    }
}, 1000);

Although everything is functioning as expected, the displayed time reflects my current timezone instead of the universal countdown I intended, since this timer indicates when the website will be launched.

Answer №1

The issue has been resolved by converting the time string into a timestamp, which successfully fixed it.

const countDownTime = new Date(1709290800000).getTime();
const currentTime = new Date().getTime();
const timeLeft = countDownTime - currentTime;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display a vibrant welcome screen on an Android WebView that ensures a visually appealing experience while the content loads for the

When launching an application, the desired behavior is as follows: Display a splash screen while simultaneously loading a URL Upon the firing of a JavaScript interface event on page load, remove the splash screen Mainactivity.java myWebView.addJavascript ...

In search of a VueJS Getter that specifically retrieves the values of the final JSON property and displays them as an array

I am currently using a Django REST API to transmit data to a VueJS front-end for display purposes. My goal is to showcase daily counts through a ChartJS graph. import { HorizontalBar } from '../BaseCharts' export default { extends: Horizontal ...

Can a fixed form of `instanceof` be used?

Is there a static equivalent of instanceof? For example, instead of using: obj1 instanceof Type is there something like: TypeA instanceof TypeB? I searched for information on this topic but couldn't find anything, so I came up with the following solu ...

"Encountering a problem with a missing object in jQuery when referencing

I'm encountering an issue with jQuery's $(this) object that's causing me to lose track of the this element in my code: $('.star').click(function (){ var id = $(this).parent().attr('id').split('rating')[ ...

What is the purpose of using Array.prototype.slice.call(nodeList) for handling DOM elements?

Many JavaScript libraries like jQuery and Zepto frequently use Array.prototype.slice.call on querySelectorAll(), getElementsByTag, or ClassName results. Despite browsing numerous questions and answers on StackOverflow about this topic, I understand that it ...

The Hapi handler function is failing to return a result

I am encountering an issue while attempting to connect hapi.js with mysql. Specifically, when defining a server route, the handler is failing to return a value. server.route({ method:'GET', path:'/hello', handler:functi ...

Unable to run for loop in vue.js

Hello, I'm a newcomer to using Vue.js and am encountering an issue with executing a simple for loop in my code. Any assistance or guidance would be greatly appreciated. Here is the snippet of my code: var Vue = require('vue'); Vue.use(requi ...

Is it possible in React to set up a callback function for when a component is passed a specific prop, without relying on the componentwill

Instead of constantly checking for updated props in componentWillUpdate, I am looking for a more efficient way to trigger the callback only when a specific prop is updated. ...

Avoiding redundant ajax requests from jquery datatable during server-side pagination

My jquery dataTable is currently set up to send a request to an MVC controller using ajax for data retrieval. While client side processing works fine, the response time is far too slow as it retrieves all records at once. To improve speed, I need to imple ...

ngCropper - dynamically adjust aspect ratio with a click of a button

I am currently working with ngCropper and I need to be able to dynamically change the aspect ratio on button click, similar to how it is done in JavaScript cropper () Below is the default option that has been set up: vm.options = { maximize: true, ...

Rotate Array Elements by N Spaces in JavaScript

Implement a function called "rotate" that will take an array and return a new array with the elements rotated by n spaces. If n is positive, the array should be rotated to the right. If n is negative, then it should be rotated to the left. If n is 0, the ...

Load images in advance using jQuery to ensure they are cached and retrieve their original sizes before other activities can proceed

When a user clicks on a thumbnail, I aim to display the full-size image in a div. To achieve this, I want to determine the original size of the image based on its source URL before it loads, allowing me to set the appropriate dimensions for the container. ...

Trouble with pinch zoom functionality in a Vue component

I have a Vue component that allows me to zoom in on an image using the mouse wheel, but I'm experiencing strange behavior with pinch zoom. When I place two fingers far apart on the screen, it zooms in significantly, and when I bring them closer togeth ...

The issue with scaling SVG files imported via Babel in Next.js is still

I've been attempting to decrease the size of my SVG icon in my next.js project. To import SVGs into my project, I included a file called .babelrc with the following: { "presets": ["next/babel"], "plugins": [" ...

Preventing window.load events from firing in JavaScript

Recently, I was playing around with a chrome extension that I had developed on various websites. The purpose of the extension was to print out the web address of the site once the entire page loaded completely. However, when I looked at the plugin's J ...

Make changes to an array in Javascript without altering the original array

I currently have an array : let originalArr = ['apple', 'plum', 'berry']; Is there a way to eliminate the item "plum" from this array without altering the originalArr? One possible solution could be: let copyArr = [...origin ...

Guide on how to retrieve a server-generated message within a jQuery script on an EJS page

Is there a way to retrieve and utilize a variable passed from a controller to an EJS page in a jQuery script? Below is the code snippet for reference: app.get('/form', (req, res) => { res.render('form', { errorMessage: & ...

Is it possible to establish a connection between Firebase Storage and HTML using TypeScript without Angular or React in IntelliJ?

My project goal is to create a functional login and register page using TypeScript. Currently, my code operates without a database, but I aim to implement Firebase for registering user credentials for easy login. I have only come across tutorials using F ...

React Native application fails to return any values from an asynchronous operation in App function

Completely new to React Native, this is my first attempt at coding. I'm struggling with returning jsx from my App() function due to an asynchronous operation within it. Here's the code that I believe clearly demonstrates my issue: import React fr ...

Tips for preserving information in the shape of Mongodb Nested schema with the help of mongoose

I am looking to design the MongoDB structure in a specific way for storing data. Here is an example of how I want it to be structured: ... After some research, this is what I have come up with for the structure: ... If I use the code below to save ...