Related
I’m working on a website that teachers are entering their availability based on their local time zone
David from California is available Monday and Tuesday at 4 PM PST for example.
I want to show that availability to everyone else internationally in their local format
John from New York can see David is available at 7 PM EST
Is there standard way of doing this without storing local time zone in the db?
I was thinking just pick a random date (or even now) and stick the hour/minute to it, save it in UTC and to display it just ignore the date part. does that sound reasonable or there is a better way?
When storing local times, the related timezone data should be stored as well. The most portable identifiers at the moment are IANA representative locations like 'America/New_York'. That way changes to standard and daylight saving offsets are accommodated so that given a particular date, you can get details for one person's time and show it as a date and time for another person's location, adjusting for their offset on that date.
The following shows an algorithm, it uses a rough function from here, but I would strongly suggest using a library like Luxon instead, I just wanted to keep this plain JS.
The following gets a time and location for one user, then displays it as an equivalent time in the location of another user. Hopefully it's something along the lines of what you want to do.
// Function from https://stackoverflow.com/a/61364310/257182
/* #param {string} isoString - ISO 8601 timestamp without timezone
** e.g. YYYY-MM-DDTHH:mm:ss or YYYY-MM-DD HH:mm:ss
** #param {string} loc - IANA representateive location
** e.g. Europe/Berlin
** #param {boolean} returnOffset - if true, return the offset instead of timestamp
** #returns {string} if returnOffset is true, offset is ±HH:mm[:ss] (seconds only if not zero)
** if returnOffset is false, equivalent ISO 8601 UTC timestamp
*/
let getUTCTime = (function() {
let n = 'numeric';
let formatterOpts = {year:n, month:n, day:n, hour:n, minute:n, second:n, hour12: false};
function parse (isoString) {
let [Y,M,D,H,m,s] = isoString.split(/[\DT\s]/);
return new Date(Date.UTC(Y,M-1,D,H,m,s));
}
function toParts(date, formatter) {
return formatter.formatToParts(date).reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, Object.create(null));
}
return function (isoString, loc, returnOffset = false) {
formatterOpts.timeZone = loc;
let formatter = new Intl.DateTimeFormat('en', formatterOpts);
let oDate = parse(isoString);
let utcDate = new Date(oDate);
let maxLoops = 3,
p, diff;
do {
p = toParts(utcDate, formatter);
diff = new Date(Date.UTC(p.year, p.month-1, p.day, p.hour, p.minute, p.second)) - oDate;
if (diff) {
utcDate.setTime(utcDate.getTime() - diff);
}
} while (diff && maxLoops--)
let dDiff = null;
if (maxLoops < 0) {
p = toParts(utcDate, formatter);
dDiff = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) - utcDate;
let msg = isoString + ' does not exist at ' + loc + ' due to ' +
'daylight saving change-over, shifting into DST';
}
let oDiff = dDiff || oDate - utcDate;
let sign = oDiff > 0? '+' : '-';
oDiff = Math.abs(oDiff);
let offH = oDiff / 3.6e6 | 0;
let offM = (oDiff % 3.6e6) / 6e4 | 0;
let offS = (oDiff % 6e4) / 1e3 | 0;
let z = n=>(n<10?'0':'')+n;
return returnOffset? `${sign}${z(offH)}:${z(offM)}${offS? ':' + z(offS) : ''}` :
utcDate.toISOString();
}
})();
// Given a local timestmap in format YYYY-MM-DDTHH:mm:ss and
// loc as IANA representative location
// Return equivalent ISO 8061 UTC timestmap
function getUTCString(timestamp, loc) {
return getUTCTime(timestamp, loc);
}
// Given a local timestmap in format YYYY-MM-DDTHH:mm:ss and
// loc as IANA representative location
// Return offset at loc as ±HH:mm[:ss]
// - seconds only included if not zero (typically pre-1900)
function getUTCOffset(timestamp, loc) {
return getUTCTime(timestamp, loc, true);
}
/* #param {string} person - name of person
** #param {string} date - date to get times in YYYY-MM-DD format
** #param {string} loc - IANA rep. loc. e.g. America/New_York
** #returns {string} timestamp for loc
*/
function showTimes(person, date, loc) {
// Get loc and time for person
let sourceLoc = data[person].loc;
let sourceTime = data[person].time;
// Get UTC date for time
let sourceDate = date + 'T' + sourceTime + ':00';
let sourceOffset = getUTCOffset(sourceDate, sourceLoc);
let utcDate = new Date(sourceDate + sourceOffset);
// Return local date for loc
return utcDate.toLocaleString('en-CA',{timeZone: loc, timeZoneName:'long', hour12: false});
}
let data = {
john: {
loc: 'America/Los_Angeles', // IANA representative location
time: '16:15' // Must be in HH:mm format
},
sally: {
loc: 'America/New_York',
time: '08:30'
}
}
let date = '2020-02-03';
let user1 = 'john';
let user2 = 'sally';
// Standard time
// Show John's time in Sally's location on Monday, 3 February 2020
console.log(
`${date} ${data[user1].time} for ${user1} in ${data[user1].loc } is\n\
${showTimes(user1,date, data[user2].loc)} for ${user2}`
);
// Daylight saving time
// Show Sally's time in John's location on Friday, 26 June 2020
date = '2020-06-26';
console.log(
`${date} ${data[user2].time} for ${user2} in ${data[user2].loc } is\n\
${showTimes(user2,date, data[user1].loc)} for ${user1}`
);
Here's an example similar to the above using Luxon:
let DateTime = luxon.DateTime;
let data = {
john: {
loc: 'America/Los_Angeles', // IANA representative location
startTime: '16:15' // Must be in HH:mm format
},
sally: {
loc: 'America/New_York',
startTime: '08:30'
}
}
console.log('----- Standard time -----');
// What is the date and time at Sally's location when John starts on
// on Monday, 3 February 2020?
let targetDate = '2020-02-03';
let johnStartString = targetDate + 'T' + data.john.startTime;
let johnStartDate = DateTime.fromISO(johnStartString, {zone: data.john.loc});
// ISO string for John's startTime
console.log('When John starts at : ' + johnStartDate.toISO());
// Create a date for Sally's loc based on John's
let sallyDate = johnStartDate.setZone(data.sally.loc);
console.log('For Sally it\'s : ' + sallyDate.toISO());
console.log('----- Daylight Saving time -----');
// What is the date and time at John's location when Sally starts on
// on Monday, 1 June 2020?
targetDate = '2020-06-01';
let sallyStartString = targetDate + 'T' + data.sally.startTime;
sallyStartDate = DateTime.fromISO(sallyStartString, {zone: data.sally.loc});
// ISO string for Sally's startTime
console.log('When Sally starts at: ' + sallyStartDate.toISO());
// Create a date for John's loc based on Sally's
let johnDate = sallyStartDate.setZone(data.john.loc);
console.log('For John it\'s : ' + johnDate.toISO());
<script src="https://cdn.jsdelivr.net/npm/luxon#1.23.0/build/global/luxon.min.js"></script>
I would store:
initial time of the day: int
end time of the day: int
original timezone: string
then, showing that to users is a UI problem.
you could calculate dynamically two dates (based on the stored times) in the original timezone and convert it to any target timezone on the fly.
an alternative is checking the time difference between original and target timezones (without calculating any date) and adding it to the initial/end times.. but I guess it's easier to go for the first option as the date classes have that kind of utils.
Keeping track of start and end hours can result in weird timezone errors.
For example, if someone selects Monday 6pm-9pm in EST, that's actually Monday 11pm - Tuesday 2am in UTC. That means the time range stored in UTC is Start: 11pm and End: 2am, which requires lots of code to work around these different scenarios.
A better idea may be to keep track of the starting hour and the number of hours until the ending time (elapsed time).
I've got a standard input type=date field that outputs a value such as "2016-03-28" when its posted, and a time picker that outputs a value like "10:30pm" when posted. I need to check if the combination of the date and time are in the past relative to the EST (eastern standard time zone). What's the best way to do this?
Here's how I did it:
var entryDate = $("input[name='launchDate']").val();
var entryTime = $("input[name='launchtime']").val();
var morningEvening = entryTime.slice(-2);
var fixedTime;
if (morningEvening === "am") {
fixedTime = entryTime.split('am').join(' AM');
} else {
fixedTime = entryTime.split('pm').join(' PM');
}
var newDate = new Date(entryDate + " " + fixedTime);
var inputDate = newDate.toLocaleString();
var offset = -5.0;
var clientDate = new Date();
var utc = clientDate.getTime() + (clientDate.getTimezoneOffset() * 60000);
var newYork = new Date(utc + (3600000*offset));
var newYorkDate = newYork.toLocaleString();
if (inputDate < newYorkDate) {
console.log("It's in the past");
} else {
console.log("It's in the future");
}
Given separate inputs for date like 2016-03-28 and time like 10:30pm you should parse both to produce a Date. To treat the date as EST (presumably US -05:00), create the date using UTC methods and add 5 hours.
A Date for "now" will have a UTC time value so you can use that as–is, then just directly compare the Date objects:
/* #param {string} ds - date string in format yyyy-mm-dd
** #param {string} ts - time string in format hh:mmap
** #returns {Date} Date with time value for equivalent EST time
*/
function parseDateTimeAsEST(ds, ts) {
var b = ds.split(/\D/);
var c = ts.split(/\D/);
c[0] = +c[0] + (/pm$/i.test(ts)? 12 : 0);
return new Date(Date.UTC(b[0], b[1]-1, b[2], c[0]+5, c[1]));
}
// Is now before or after 2016-03-28T22:30:00-05:00?
document.write(new Date() < parseDateTimeAsEST('2016-03-28','10:30pm')? 'before' : 'after');
document.write('<br>');
// Is now before or after 2016-04-01T01:30:00-05:00?
document.write(new Date() < parseDateTimeAsEST('2016-04-01','01:30am')? 'before' : 'after');
Hi guys need some help,
here is my code
function getCurrentDateByGMT(finalTimezone){
var now = new Date();
var localTime = now.getTime();
var finalGMT = now.getTimezoneOffset() - finalTimezone;
var localOffset = finalGMT * 60000; // where 60000 is equals to 1 min
return new Date(localTime + localOffset);
}
this function gets the current date by inputed gmt -480 where gmt + 8 multiplied by -60
but whenever i changed my computer timezone the countdown also changed.
after i refresh the browser it went back to normal countdown without changing the timezone.
i wonder why can someone help me with this ? thanks in advance and also for grammar correction you are welcome to edit this question thanks thanks.
also, can someone explain this to me thanks again
update :
okay here's my full code
function getTimeRemaining(endtime,gmt){
var t = Date.parse(endtime) - Date.parse(getCurrentDateByGMT(gmt));
var seconds = Math.floor( (t/1000) % 60 );
var minutes = Math.floor( (t/1000/60) % 60 );
var hours = Math.floor( (t/(1000*60*60)) % 24 );
var days = Math.floor( t/(1000*60*60*24) );
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(hour,minute,second,endtime,gmt){
var locHour = document.getElementById(hour);
var locMinute = document.getElementById(minute);
var locSecond = document.getElementById(second);
if(!endtime){
console.log(false);
}else{
function updateClock(){
var countDown = getTimeRemaining(endtime,gmt);
console.log(countDown);// here is the console that output the image above
if(countDown.total>=0){
locHour.innerHTML = ('0' + countDown.hours).slice(-2);
locMinute.innerHTML = ('0' + countDown.minutes).slice(-2);
locSecond.innerHTML = ('0' + countDown.seconds).slice(-2);
}else{
console.log("happend");
clearInterval(timeinterval);
initializeClock(hour,minute,second,generateTimerPerPeriod(),gmt);
}
}
updateClock(); // run function once at first to avoid delay
var timeinterval = setInterval(updateClock,1000);
}
}
function generateTimerPerPeriod(){
var schedule = [['00:00:00', '11:59:59'],['12:00:00', '15:59:59'],['16:00:00', '19:59:59'],['20:00:00', '23:59:59']];
var currentTime = getCurrentDateByGMT(getTimezone('+8'));
var currentPeriod = new Date(currentTime);
for(var timeCtr = 0; timeCtr < schedule.length ; timeCtr++){
var startDate = schedule[timeCtr][0].split(':');
var endDate = schedule[timeCtr][1].split(':');
if(currentTime > currentPeriod.setHours(startDate[0],startDate[1],startDate[2],0) && currentTime < currentPeriod.setHours(endDate[0],endDate[1],endDate[2],0)){
var periodDate = new Date(currentPeriod.setHours(endDate[0],endDate[1],endDate[2],0));
// console.log(" enddate " +periodDate);
return periodDate;
}
}
return false;
}
function getCurrentDateByGMT(finalTimezone){
var myOldDateObj = new Date();
var myTZO = -480;
var myNewDate=new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
console.log(" newdate "+ myNewDate);
var now = new Date();
var localTime = now.getTime();
var finalGMT = now.getTimezoneOffset() - finalTimezone;
var localOffset = finalGMT * 60000; // where 60000 is equals to 1 min
return new Date(localTime + localOffset);
}
function getTimezone(timezone){
return timezone * (-60);
}
Update :
how about this one ?
function getCurrentTimeGMT8(){
var d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var now = new Date(utc + (3600000*8));
var hour = addZero(now.getHours());
var min = addZero(now.getMinutes());
var sec = addZero(now.getSeconds());
var tz = "GMT+8";
var time = hour +':'+ min +':'+ sec + " " + tz;
return time;
}
A few things:
The getTime function of the Date object always returns values in terms of UTC, so calling it localTime is incorrect. That means your finalGMT and localOffset values are also incorrect because you're assuming the localTime value has been adjusted for the local offset, and it hasn't. Your code should just be:
Any time you construct a new Date by changing the underlying timestamp (like you do with new Date(localTime + localOffset), and also when you create your myNewDate variable), you're not actually changing the time zone. You're just moving the Date to a different moment in time, which is probably not the one you intended. The Date object will still represent time in the current local time zone, and will still follow the DST transition rules for the current local time zone. If you intended it to represent some other time zone, that can get in the way.
Note that you can still calculate the UTC-based numeric timestamp from the current time via Date.now() (or via Date.UTC with user input values) and adding the desired offset. You just can't then take that timestamp and put it in a Date object unless you intend it to reflect the local time zone. If you need to know the year, month, day, hour, minute, second of that timestamp in any other time zone than the local zone, you'll need a library such as moment.js, or some advanced algorithms of your own.
You asked about changing the time zone in the OS. You should recognize that the effect of this is inconsistent across browsers, versions, and operating systems. Many browsers (such as Chrome) will not pick up the new time zone until the browser process is completely terminated and restarted. However, some browsers (such as IE) will update the time zone without requiring a restart. If you need the user's time zone offset, you shouldn't cache it.
Keep in mind that a number can only represent an offset. A time zone can have more than one offset, either due to daylight saving time, or due to changes over its history. Read "Time Zone != Offset" in the timezone tag wiki.
In your case, your countdown timer is working only with offsets. If that's your intent, then fine. You can certainly take a date, time, and offset as input values. Just don't assume that the current offset from new Date().getTimezoneOffset() will necessarily be the correct offset for ALL dates and times in the user's time zone.
I do not know why it does not work?
Can you help me please?
function calcTime(city, offset) {
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));
return nd.toLocaleString();
}
var Paris =setInterval( function() { calcTime('gmt', '+1'); }, 500 );
I do not get the value of calcTime in the Paris variable
setInterval returns an interval pointer, not the value of the function.
You likely want this instead
function calcTime(city, offset) {
var d = new Date();
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var nd = new Date(utc + (3600000*offset));
return nd.toLocaleString();
}
var parisTId =setInterval( function() {
document.getElementById("paris").innerHTML=calcTime('gmt', '+1');
}, 500 );
It seems you're trying to get the current time in a place with a particular offset in hours (presumably decimal hours since not all timezone offsets are full hours). You can do that fairly simply using:
// Offset is per javascript timezone offset, i.e. minutes to subtract
// from UTC to get local time, so for a place that is UTC+01:00 use -60
function calcTime(offset) {
var d = new Date();
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() - offset);
return d;
}
Note that using toLocaleString will report the timezone of the users current location, not the timezone that the date has been adjusted for, so you might want to build your own string that has the correct offset (say based on ISO 8601).
What is the best method to get the clients local time irrespective of the time zone of clients system? I am creating an application and i need to first of all get the exact time and date of the place from where the client is accessing. Even detecting the ip address of client system has a drawback or detecting the time zone of client system may be risky at times. So, is there any way out which could be really reliable and not vulnerable to error because displaying wrong time and date to client is something very embarassing.
In JavaScript? Just instantiate a new Date object
var now = new Date();
That will create a new Date object with the client's local time.
Nowadays you can get correct timezone of a user having just one line of code:
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions
You can then use moment-timezone to parse timezone like:
const currentTime = moment().tz(timezone).format();
Try
let s= new Date().toLocaleString();
console.log(s);
If you want to know the timezone of the client relative to GMT/UTC here you go:
var d = new Date();
var tz = d.toString().split("GMT")[1].split(" (")[0]; // timezone, i.e. -0700
If you'd like the actual name of the timezone you can try this:
var d = new Date();
var tz = d.toString().split("GMT")[1]; // timezone, i.e. -0700 (Pacific Daylight Time)
UPDATE 1
Per the first comment by you can also use d.getTimezoneOffset() to get the offset in minutes from UTC. Couple of gotchas with it though.
The sign (+/-) of the minutes returned is probably the opposite of what you'd expect. If you are 8 hours behind UTC it will return 480 not -480. See MDN or MSDN for more documentation.
It doesn't actually return what timezone the client is reporting it is in like the second example I gave. Just the minutes offset from UTC currently. So it will change based on daylight savings time.
UPDATE 2
While the string splitting examples work they can be confusing to read. Here is a regex version that should be easier to understand and is probably faster (both methods are very fast though).
If you want to know the timezone of the client relative to GMT/UTC here you go:
var gmtRe = /GMT([\-\+]?\d{4})/; // Look for GMT, + or - (optionally), and 4 characters of digits (\d)
var d = new Date().toString();
var tz = gmtRe.exec(d)[1]; // timezone, i.e. -0700
If you'd like the actual name of the timezone try this:
var tzRe = /\(([\w\s]+)\)/; // Look for "(", any words (\w) or spaces (\s), and ")"
var d = new Date().toString();
var tz = tzRe.exec(d)[1]; // timezone, i.e. "Pacific Daylight Time"
In order to get local time in pure Javascript
use this built in function
// return new Date().toLocaleTimeString();
See below example
function getLocaltime(){
return new Date().toLocaleTimeString();
}
console.log(getLocaltime());
directly like this :
new Date((new Date().setHours(new Date().getHours() - (new Date().getTimezoneOffset() / 60)))).toISOString()
more details in this utility function
function getLocaLTime() {
// new Date().getTimezoneOffset() : getTimezoneOffset in minutes
//for GMT + 1 it is (-60)
//for GMT + 2 it is (-120)
//..
let time_zone_offset_in_hours = new Date().getTimezoneOffset() / 60;
//get current datetime hour
let current_hour = new Date().getHours();
//adjust current date hour
let local_datetime_in_milliseconds = new Date().setHours(current_hour - time_zone_offset_in_hours);
//format date in milliseconds to ISO String
let local_datetime = new Date(local_datetime_in_milliseconds).toISOString();
return local_datetime;
}
Just had to tackle this so thought I would leave my answer. jQuery not required I used to update the element as I already had the object cached.
I first wrote a php function to return the required dates/times to my HTML template
/**
* Gets the current location time based on timezone
* #return string
*/
function get_the_local_time($timezone) {
//$timezone ='Europe/London';
$date = new DateTime('now', new DateTimeZone($timezone));
return array(
'local-machine-time' => $date->format('Y-m-d\TH:i:s+0000'),
'local-time' => $date->format('h:i a')
);
}
This is then used in my HTML template to display an initial time, and render the date format required by javascript in a data attribute.
<span class="box--location__time" data-time="<?php echo $time['local-machine-time']; ?>">
<?php echo $time['local-time']; ?>
</span>
I then used the getUTCHours on my date object to return the time irrespective of the users timezone
The getUTCHours() method returns the hour (from 0 to 23) of the
specified date and time, according to universal time.
var initClocks = function() {
var $clocks = $('.box--location__time');
function formatTime(hours, minutes) {
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
return {
hours: hours,
minutes: minutes
}
}
function displayTime(time, $clockDiv) {
var currentTime = new Date(time);
var hours = currentTime.getUTCHours();
var minutes = currentTime.getUTCMinutes();
var seconds = currentTime.getUTCSeconds();
var initSeconds = seconds;
var displayTime = formatTime(hours, minutes);
$clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);
setInterval(function() {
if (initSeconds > 60) {
initSeconds = 1;
} else {
initSeconds++;
}
currentTime.setSeconds(initSeconds);
hours = currentTime.getUTCHours();
minutes = currentTime.getUTCMinutes();
seconds = currentTime.getUTCSeconds();
displayTime = formatTime(hours, minutes);
$clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);
}, 1000);
}
$clocks.each(function() {
displayTime($(this).data('time'), $(this));
});
};
I then use the setSeconds method to update the date object based on the amount of seconds past since page load (simple interval function), and update the HTML
The most reliable way I've found to display the local time of a city or location is by tapping into a Time Zone API such as Google Time Zone API. It returns the correct time zone, and more importantly, Day Light Savings Time offset of any location, which just using JavaScript's Date() object cannot be done as far as I'm aware. There's a good tutorial on using the API to get and display the local time here:
var loc = '35.731252, 139.730291' // Tokyo expressed as lat,lng tuple
var targetDate = new Date() // Current date/time of user computer
var timestamp = targetDate.getTime() / 1000 + targetDate.getTimezoneOffset() * 60 // Current UTC date/time expressed as seconds since midnight, January 1, 1970 UTC
var apikey = 'YOUR_TIMEZONE_API_KEY_HERE'
var apicall = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + loc + '×tamp=' + timestamp + '&key=' + apikey
var xhr = new XMLHttpRequest() // create new XMLHttpRequest2 object
xhr.open('GET', apicall) // open GET request
xhr.onload = function() {
if (xhr.status === 200) { // if Ajax request successful
var output = JSON.parse(xhr.responseText) // convert returned JSON string to JSON object
console.log(output.status) // log API return status for debugging purposes
if (output.status == 'OK') { // if API reports everything was returned successfully
var offsets = output.dstOffset * 1000 + output.rawOffset * 1000 // get DST and time zone offsets in milliseconds
var localdate = new Date(timestamp * 1000 + offsets) // Date object containing current time of Tokyo (timestamp + dstOffset + rawOffset)
console.log(localdate.toLocaleString()) // Display current Tokyo date and time
}
} else {
alert('Request failed. Returned status of ' + xhr.status)
}
}
xhr.send() // send request
From: Displaying the Local Time of Any City using JavaScript and Google Time Zone API
I found this function is very useful during all of my projects. you can also use it.
getStartTime(){
let date = new Date();
var tz = date.toString().split("GMT")[1].split(" (")[0];
tz = tz.substring(1,5);
let hOffset = parseInt(tz[0]+tz[1]);
let mOffset = parseInt(tz[2]+tz[3]);
let offset = date.getTimezoneOffset() * 60 * 1000;
let localTime = date.getTime();
let utcTime = localTime + offset;
let austratia_brisbane = utcTime + (3600000 * hOffset) + (60000 * mOffset);
let customDate = new Date(austratia_brisbane);
let data = {
day: customDate.getDate(),
month: customDate.getMonth() + 1,
year: customDate.getFullYear(),
hour: customDate.getHours(),
min: customDate.getMinutes(),
second: customDate.getSeconds(),
raw: customDate,
stringDate: customDate.toString()
}
return data;
}
this will give you the time depending on your time zone.
Thanks.
Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api
fetch("https://worldtimeapi.org/api/ip")
.then(response => response.json())
.then(data => console.log(data.dst,data.datetime));
I needed to report to the server the local time something happened on the client. (In this specific business case UTC provides no value). I needed to use toIsoString() to have the format compatible with .Net MVC but toIsoString() this always converts it to UTC time (which was being sent to the server).
Inspired by the 'amit saini' answer I now use this
function toIsoStringInLocalTime(date) {
return new Date((date.getTime() + (-date.getTimezoneOffset() * 60000))).toISOString()
}
You can also make your own nodeJS endpoint, publish it with something like heroku, and access it
require("http").createServer(function (q,r) {
r.setHeader("accees-control-allow-origin","*")
r.end(Date.now())
}).listen(process.env.PORT || 80)
Then just access it on JS
fetch ("http://someGerokuApp")
.then(r=>r.text)
. then (r=>console.log(r))
This will still be relative to whatever computer the node app is hosted on, but perhaps you can get the location somehow and provide different endpoints fit the other timezones based on the current one (for example if the server happens to be in California then for a new York timezone just add 1000*60*60*3 milliseconds to Date.now() to add 3 hours)
For simplicity, if it's possible to get the location from the server and send it as a response header, you can just do the calculations for the different time zones in the client side
In fact using heroku they allow you to specify a region that it should be deployed at https://devcenter.heroku.com/articles/regions#specifying-a-region you can use this as reference..
EDIT
just realized the timezone is in the date string itself, can just pay the whole thing as a header to be read by the client
require("http").createServer(function (q,r) {
var d= new Date()
r.setHeader("accees-control-allow-origin","*")
r.setHeader("zman", d.toString())
r.end(d.getTime())
}).listen(process.env.PORT || 80)
new Date(Date.now() + (-1*new Date().getTimezoneOffset()*60000)).toISOString()
my code is
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
<body onload=display_ct();>
<span id='ct' ></span>
</body>
Try on this way
function timenow(){
var now= new Date(),
ampm= 'am',
h= now.getHours(),
m= now.getMinutes(),
s= now.getSeconds();
if(h>= 12){
if(h>12) h -= 12;
ampm= 'pm';
}
if(m<10) m= '0'+m;
if(s<10) s= '0'+s;
return now.toLocaleDateString()+ ' ' + h + ':' + m + ':' + s + ' ' + ampm;
}
toLocaleDateString()
is a function to change the date time format like toLocaleDateString("en-us")