Skip to content
Advertisement

Adding dynamic date to a static webpage

I want my static webpage timezone needs to be relative to CST, so if client(CST) open this file it should show CST date and Myself(IST) if I open this also it should show only the CST, could anyone please help me on this

HTML file-

<span id="spanDate"></span>

JS file-

var months = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];       
var tomorrow = new Date();       
document.getElementById("spanDate").innerHTML = months[tomorrow.getMonth()] + " " + 
tomorrow.getDate()+ ", " + tomorrow.getFullYear();

Advertisement

Answer

You shouldn’t try to assemble a date string yourself. Both the names of the month, as well as the typical arrangement of the year, month, and day parts are very locale-specific. Instead, use toLocaleString, which has options to control output, including which time zone to use.

I’ll assume by “CST” you meant the “Central Standard Time” in the US. If you actually meant “China Standard Time”, or “Cuba Standard Time”, you’ll need to change the time zone ID in the code below, to the desired IANA time zone identifier.

Also, your code used the word “tomorrow”, so I presume you want tomorrow’s date – but you were only getting today’s date. If you need today’s date, you can take out the second step in the code below.

// Get the current point in time
const timestamp = new Date();

// advance by 24 hours, to get to tomorrow
timestamp.setTime(timestamp.getTime() + (24 * 60 * 60 * 1000));

// format and output the result
const locale = undefined; // use the user's current locale (language/region)
document.getElementById("spanDate").innerHTML = timestamp.toLocaleString(locale, {
  timeZone: 'America/Chicago', // use the US Central Time Zone
  year: 'numeric', // include the year as a number
  month: 'long',   // include the month as the long name
  day: 'numeric'   // include the day as a number
});
<span id="spanDate"></span>

Also, note that while advancing by 24 hours to get tomorrow’s date is the easiest approach, there are some edge cases near daylight saving time transitions in certain time zones where it could be a bit off (due to having 23 or 25 hours on such days, etc.). Working around that is currently quite complicated unless you use a library like Luxon. But if you don’t require such precision, then 24 hours is fine.

Advertisement