I have created a small snippet, which is supposed to return the UTC time value for the user's country based on their computer settings. However, I would be really thankful if you can test the snippet and give me some feedback if it managed to display the correct UTC value for your country. Any feedback would be high appreciated. Thank you in advance.
PS: What I learned from Wikipedia while researching how to tackle this problem is that UTC is not a time zone, therefore the 1 hour change in some countries between the winter and summer time would not affect the UTC value. However, please note that UTC is equal to GMT (Winter time) therefore for the countries which are using the summer time as of writing this post an hour has to be extracted to get the GMT (Winter Time), which in theory has to be equal to the UTC value.
var currentDate = new Date();
var fetchYear = currentDate.getFullYear();
var fetchMonth = currentDate.getMonth();
var fetchDay = currentDate.getDate();
var fetchHour = currentDate.getHours();
var fetchMinutes = currentDate.getMinutes();
var fetchSeconds = currentDate.getSeconds();
var fetchMilliseconds = currentDate.getMilliseconds();
var referenceDate = new Date(fetchYear, 0, fetchDay, fetchHour, fetchMinutes, fetchSeconds, fetchMilliseconds)
var currentDateToString = currentDate.toString().match(/[+|-].{4}/).toString();
var referenceDateToString = referenceDate.toString().match(/[+|-].{4}/).toString();
if (currentDateToString == referenceDateToString){
document.getElementById("utcValue").innerHTML = "Output: UTC " + currentDateToString;
} else {
document.getElementById("utcValue").innerHTML = "Output: UTC " + referenceDateToString;
}
<div id="utcValue"></div>
Related
I got the following string: "2022/05/01 03:10:00" and I need to create a Date object forcing it to use Chile's UTC offset.
The problem is that because of Daylight saving time (DST) the offset changes twice a year.
How can get that Date object, for example, using the "America/Santiago" TZ db name?
Something like:
new Date("2022/05/01 03:10:00" + getUtcOffset("America/Santiago")).
function getUtcOffset(tzDbName) {
..
}
Returns -3 or -4, depending the time in the year.
EDIT:
I ended using a nice trick for determining if DST was on or off.
reference
const dst = hasDST(new Date(strDate));
function hasDST(date = new Date()) {
const january = new Date(date.getFullYear(), 0, 1).getTimezoneOffset();
const july = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
return Math.max(january, july) !== date.getTimezoneOffset();
}
Then I could create the date with the correct timezone depending on that variable.
if (dst) {
let d = new Date(strDate + " GMT-0300");
return d;
} else {
let d = new Date(strDate + " GMT-0400");
return d;
}
Thanks everyone!
EDIT2:
I finally found a very nice library that does exactly what I was looking for:
https://date-fns.org/v2.28.0/docs/Time-Zones#date-fns-tz
const { zonedTimeToUtc, utcToZonedTime, format } = require('date-fns-tz')
const utcDate = zonedTimeToUtc('2022-05-05 18:05', 'America/Santiago')
This has been discussed before here.
Haven't tested it, but it appears that the simplest solution is:
// Example for Indian time
let indianTime = new Date().toLocaleTimeString("en-US",
{timeZone:'Asia/Kolkata',timestyle:'full',hourCycle:'h24'})
console.log(indianTime)
You can check the link for more complex answers and libraries
Generals notes
To get the time zone name use:
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)
To get the difference from UTC (in minutes) use:
var offset = new Date().getTimezoneOffset();
console.log(offset);
// if offset equals -60 then the time zone offset is UTC+01
I discovered that this URL api-sunrise-sun sunset gives date time in UTC format however I want to convert on the fly to local time irrespective where my webpage is opened ! How would I achieve that?
I suppose you are showing the time after successfully getting the json. Try this:
//today's date, or whatever
var t_date = new Date().toLocaleDateString();
//time from json. example: 10:04:34 PM
var t_from_json = response["results"]["sunrise"]
var utc_date = new Date( t_date + " " + t_from_json + " UTC")
//Date 2017-02-21T22:04:34.000Z
//two options:
utc_date.toString();
//"Tue Feb 21 2017 19:04:34 GMT-0300 (CLST)"
var offset = new Date().getTimezoneOffset();
utc_date.setMinutes(utc_date.getMinutes() - offset);
//Date 2017-02-21T19:04:34.000Z
I created a jsfiddle here
e.onclick=timeConverter('2014-05-02 22:03:34'); //IF I PASS THIS STRING AS DATE, I GOT THIS: 2,May 2014 22:3:34
e.onclick=timeConverter('2014-05-02T22:03:34.890Z'); //IF I PASS THIS STRING AS DATE, I GOT THIS: 3,May 2014 6:3:34
Does "T" or "Z" in the string matters? If someone can enlighten me, thank you.
HTML:
<input type="button" id="format" value="Format Date">
Javascript:
function timeConverter(UNIX_timestamp){
var s = new Date(UNIX_timestamp).getTime()/1000;
var a = new Date(s*1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
//var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
alert(time);
}
var e = document.getElementById('format');
e.onclick=timeConverter('2014-05-02 22:03:34');
//e.onclick=timeConverter('2014-05-02T22:03:34.890Z');
Check this document here which is a extract of ISO 8601.
'T' is just meant as separator between Time and Date.
'Z' is a special indicator for UTC (+00:00) as time zone
The Problem is, '2014-05-02 22:03:34' is kinda chrome specific formatting as far as i know, which treats this time as your local time. So the difference of exactly 8 hours appear.
So to be on the safe side, always remember to put the Separator in and keep in mind what timezone you are referring to.
see this wiki-article , the Z in your string means that you are using the
local timezone, so thats the reason for the differnce in your alert
According to ECMA-262, accepted datetime format is:
[+YY]YYYY[-MM[-DD]][THH:mm[:ss[.sss]]]Z
Where Z is either Z or + , - followed by HH:mm. If you specify Z at the end of your timestamp, it means the time is in UTC. Since you are living in GMT+8, your browser adds 8 hours to convert it to local time. Therefore, you get 3,May 2014 6:3:34 instead of 2,May 2014 22:3:34.
How to convert milliseconds in mm/dd/yyyy in different timezones.
I have a datepicker, when I press save, it saves the date in millisecond.
The saved millisecond should display date according to timezone date.
My Code:
var millisecond=1378792800000;
var date=new Date(millisecond);
var date_month = date.getMonth() + 1;
display_date = date_month + "/" + date.getDate() + "/" + date.getFullYear();
The date is differ in different timezones
When my timezone is India GMT then it is 09/10/2013
and when I change my timezone to US Mountain it change to 09/09/2013.
So how can I handle different timezone in javascript.
I would suggest using a third party script such as moment.js to make your life easier
Here is an example: http://jsfiddle.net/cyxgJ/
var ms = 1378792800000;
var date = new moment(ms);
// see <http://momentjs.com/docs/#/manipulating/timezone-offset/>
date = date.zone(120);
document.body.innerHTML = date;
I am trying to create a simple script that gives me the next recycling date based on a biweekly schedule starting on Wed Jul 6, 2011. So I've created this simple function...
function getNextDate(startDate) {
if (today <= startDate) {
return startDate;
}
// calculate the day since the start date.
var totalDays = Math.ceil((today.getTime()-startDate.getTime())/(one_day));
// check to see if this day falls on a recycle day
var bumpDays = totalDays%14; // mod 14 -- pickup up every 14 days...
// pickup is today
if (bumpDays == 0) {
return today;
}
// return the closest day which is in 14 days, less the # of days since the last
// pick up..
var ms = today.getTime() + ((14- bumpDays) * one_day);
return new Date(ms);
}
and can call it like...
var today=new Date();
var one_day=1000*60*60*24; // one day in milliseconds
var nextDate = getNextDate(new Date(2011,06,06));
so far so good... but when I project "today" to 10/27/2011, I get Tuesday 11/8/2011 as the next date instead of Wednesday 11/9/2011... In fact every day from now thru 10/26/2011 projects the correct pick-up... and every date from 10/27/2011 thru 2/28/2012 projects the Tuesday and not the Wednesday. And then every date from 2/29/2012 (leap year) thru 10/24/2012 (hmmm October again) projects the Wednesday correctly. What am I missing? Any help would be greatly appreciated..
V
The easiest way to do this is update the Date object using setDate. As the comments for this answer indicate this isn't officially part of the spec, but it is supported on all major browsers.
You should NEVER update a different Date object than the one you did the original getDate call on.
Sample implementation:
var incrementDate = function (date, amount) {
var tmpDate = new Date(date);
tmpDate.setDate(tmpDate.getDate() + amount)
return tmpDate;
};
If you're trying to increment a date, please use this function. It will accept both positive and negative values. It also guarantees that the used date objects isn't changed. This should prevent any error which can occur if you don't expect the update to change the value of the object.
Incorrect usage:
var startDate = new Date('2013-11-01T11:00:00');
var a = new Date();
a.setDate(startDate.getDate() + 14)
This will update the "date" value for startDate with 14 days based on the value of a. Because the value of a is not the same is the previously defined startDate it's possible to get a wrong value.
Expanding on Exellian's answer, if you want to calculate any period in the future (in my case, for the next pay date), you can do a simple loop:
var today = new Date();
var basePayDate = new Date(2012, 9, 23, 0, 0, 0, 0);
while (basePayDate < today) {
basePayDate.setDate(basePayDate.getDate()+14);
}
var nextPayDate = new Date(basePayDate.getTime());
basePayDate.setDate(nextPayDate.getDate()-14);
document.writeln("<p>Previous pay Date: " + basePayDate.toString());
document.writeln("<p>Current Date: " + today.toString());
document.writeln("<p>Next pay Date: " + nextPayDate.toString());
This won't hit odd problems, assuming the core date services work as expected. I have to admit, I didn't test it out to many years into the future...
Note: I had a similar issue; I wanted to create an array of dates on a weekly basis, ie., start date 10/23/2011 and go for 12 weeks. My code was more or less this:
var myDate = new Date(Date.parse(document.eventForm.startDate.value));
var toDate = new Date(myDate);
var week = 60 * 60 * 24 * 7 * 1000;
var milliseconds = toDate.getTime();
dateArray[0] = myDate.format('m/d/Y');
for (var count = 1; count < numberOccurrences; count++) {
milliseconds += week;
toDate.setTime(milliseconds);
dateArray[count] = toDate.format('m/d/Y');
}
Because I didn't specify the time and I live in the US, my default time was midnight, so when I crossed the daylight savings time border, I moved into the previous day. Yuck. I resolved it by setting my time of day to noon before I did my week calculation.