My timezone is GMT+2.
When local time '2020-05-21 01:00'
that should mean '2020-05-20 23:00' in UTC time zone (GMT+0)
So days difference should say: 1
This code deosnt give that result. Anyone have idea why ?
EDIT: Simply said: Saturday 1am in my place is Friday 11pm in UTC. so there SHOULD be 1 day difference. Here is live code sample
https://stackblitz.com/edit/moment-js-playground-vteexd?embed=1&file=index.ts
Internally they are the same date. To prove that, try comparing their timestamps now.format('X') === utc.format('X').
As a solution, I would propose using moment durations to measure the time difference, and using .days() to get the desired value.
This could be of help.
Here I'm going to give solution to my own question:
import moment from "moment-timezone";
//test for GMT+1
var now = moment().startOf("day").add(1, "hours");
console.log(now.format(), " now", now.format('dddd'));
let res= GetDayOffsetUTC(now);
console.log("Day diff: ", res);
// Get DAY difference between local and UTC time
// Responses:
// -1 : your local time is 1 day ahead of UTC
// 1 : your local time is 1 day after UTC
// 0 : your local time is same day as UTC
function GetDayOffsetUTC(date) {
const utcOffset = date.utcOffset();
const utc = date.clone().add(-utcOffset, "minutes");
const dayDiff = utc.startOf("day").diff(date.startOf("day"), "days");
return dayDiff;
}
Related
I need to make sure if its after 21 hours in UTC or 4 pm est to set the initial day in the date picker as the next day although i need help with the logic of getting a date time object of the last time when it was last 21 hours in UTC.
For example if its 22 hours in utc the last time it was 21 hours was a hour ago so i just use the same utc date and subtract a hour
although a couple hours after it will be a new utc date how do i represent that? Does any one have any ideas?
Im using datetime and using custom color picker libraries is not the solution i'm interested in. I just need help on the logic of how to set Initial date/ Current date in my custom calendar picker with the criteria that after 21 hours utc it should move to the next day.
You just need to test the UTC hour, which is returned by getUTCHours, so:
function getDate(date = new Date()) {
// Copy date so don't affect original
let d = new Date(date);
// If 2100 UTC or later, set to tomorrow UTC
if (d.getUTCHours() > 20) {
d.setUTCDate(d.getUTCDate() + 1);
}
// Set the time to 2100
d.setUTCHours(21,0,0,0);
return d;
}
// Current value
console.log(getDate());
// Value for 2021-03-01T22:00:00Z
console.log(getDate(new Date(Date.UTC(2021,2,1,22)))); // T21:00:00.000Z
I have an event that happens every day at 1AM UTC. I am trying to find the easiest way to show the local time to the user:
document.getElementById('local').innerHTML=(new Date(3600000)).toLocaleTimeString();
works half the year. But it does not take in to account day light savings time so right now in places that use day light savings it is off by an hour. It is correct for those places that don't use day light savings time though.
If you want to show an event that occurs at 1 am UTC in a locale aware format, you have to include the date portion as well. You can't just use new Date(3600000) as that is 1970-01-01 01:00:00 UTC, so you'll get the timezone offset for then (which might be different because of daylight saving or because the locale has changed its offset).
So if you want every 1 am UTC for the next 7 days, then:
var d = new Date();
d.setUTCHours(1,0,0,0);
for (var i=7; i>0; i--) {
console.log(d.toLocaleString());
d.setUTCDate(d.getUTCDate() + 1);
}
const timeZoneValue = "Asia/Kolkata";
const localeStr = "en-US";
document.getElementById('local').innerHTML=(new Date().toLocaleString(localeStr , {timeZone: timeZoneValue}));
var oneam = new Date(new Date().setUTCHours(1,0,0,0));
console.log(oneam.toString())
will get today at 1am UTC, as a local time string.
I want to count down the days until a particular event using momentjs but I'm getting an unexpected result.
With today's date being 17th April, and the event date being 14th May, I want the resulting number of days to be 27, however my code gives me a result of 57. What's wrong?
function daysRemaining() {
var eventdate = moment([2015, 5, 14]);
var todaysdate = moment();
return eventdate.diff(todaysdate, 'days');
}
alert(daysRemaining());
When creating a moment object using an array, you have to take note that months, hours, minutes, seconds, and milliseconds are all zero indexed. Years and days of the month are 1 indexed. This is to mirror the native Date parameters.
Reference
So either change the month to 4 to reflect May or parse the date as an ISO 8601 string
function daysRemaining() {
var eventdate = moment("2015-05-14");
var todaysdate = moment();
return eventdate.diff(todaysdate, 'days');
}
alert(daysRemaining());
Just to add for anyone else that comes across this - there's actually a helper that does the phrasing etc for you:
https://momentjs.com/docs/#/displaying/to/
/* Retrieve a string describing the time from now to the provided date */
daysUntil: function(dateToCheckAgainst){
return new moment().to(moment(dateToCheckAgainst));
}
// Sample outputs
"in three months"
"in two months"
"in 25 days"
That's because months are zero indexed. So 5 is actually June ;)
I need to pick a future date from calender, suppose the date I am selecting is 10/14/2014, now what I want is to send the date with the time to server, so that at server end it always reaches as 6am time in PST timezone and the format of date should be UTC.
What I am doing is
targetDate = new Date($("#calendar").val());
targetDate = targetDate.toUTCString();
targetDate = targetDate.addHours(14);
My understanding is that PST timezone is -8:00 so I have added 14 hours to the UTC time so that time becomes 6:00am PST
The problem I am facing is that it is not letting me to add 14 hours since the object has already been converted to string.
addHours is the custom function I am having to add the hours in given time.
If I write
targetDate = new Date($("#calendar").val());
targetDate = targetDate.addHours(14);
targetDate = targetDate.toUTCString();
then it works good but in this case problem is time will always be different when the request is coming from different timezones.
Any help is appreciated.
This worked for me:
var myDate = new Date(1633071599000)
var pstDate = myDate.toLocaleString("en-US", {
timeZone: "America/Los_Angeles"
})
console.log(pstDate)
Which outputs "9/30/2021, 11:59:59 PM"
You said:
My understanding is that PST timezone is -8:00 so I have added 14 hours to the UTC time so that time becomes 6:00am PST
Uh - no. That will put you on the following day. If you wanted to stay in PST, you would subtract 8 hours from the UTC time. -8:00 means that it is 8 hours behind UTC.
However, the Pacific Time zone isn't just fixed at PST. It alternates between PST (-8) and PDT (-7) for daylight saving time. In order to determine the correct offset, you need to use a library that implements the TZDB database. Refer to this duplicate answer here.
The only way to do it without a fancy library is to actually be in the pacific time zone. JavaScript will convert UTC dates to the local time zone for display, and it will use the correct offset. But it only knows about the local time zone. If Pacific Time is not your local time zone, then you must use a library.
Suggest you look at DateJS http://code.google.com/p/datejs/ or http://www.datejs.com/. Handles PDT for you.
Here is an alternative for you:
Use: Date.UTC(year, month, day, hours, minutes, seconds, ms)
Example:
For 1 Jan 2013 6AM PST
var date = new Date(Date.UTC(2013, 0, 1, 14, 0, 0))
console.log(date.toUTCString());
Prints: "Tue, 01 Jan 2013 14:00:00 GMT"
var date = new Date();
var utcDate = new Date(date.toUTCString());
utcDate.setHours(utcDate.getHours()-8);
var usDate = new Date(utcDate);
console.log(usDate);
document.getElementById('tmp_button-48523').addEventListener('click', function() {
let d = new Date();
let localTime = d.getTime();
let localOffset = d.getTimezoneOffset() * 60000;
let utc = localTime + localOffset;
let target_offset = -7;//PST from UTC 7 hours behind right now, will need to fix for daylight
let los_angles = utc+(3600000*target_offset);
nd = new Date(los_angles);
let current_day = nd.getDay();
let hours = nd.getHours();
let mins = nd.getMinutes();
alert("los_angles time is " + nd.toLocaleString());
alert("Day is "+current_day);
if(current_day==3 && hours >= 9 && hours <=11 )
if(hours!=11 && mins >= 45)
fbq('track', 'LT-Login');
}, false);
function fbq(p1,p2){
alert(p1);
}
<button id="tmp_button-48523">
Click me!
</button>
Here is the code that created to track fb pixel on Wednesdays between 9:45am PST and 11:00am PST
Mostly comment:
I need to pick a future date from calender, suppose the date I am
selecting is 10/14/2014,
Since there isn't a 14th month, I suppose you mean 14 October, 2014. Since this is an international forum, better to use an unambiguous format.
… and the format of date should be UTC
UTC is not a format, it's a standard time.
I think you are confused. If you want say 2014-10-14T06:00:00-08:00 in UTC, then the equivalent is 2014-10-14T14:00:00Z.
You are using the toUTCString method, but it is implementation dependent, so you'll get different results in different browsers. You probably want the toISOString method, but it's ES5 and not implemented in all browsers.
You need to provide some examples of how you want times to be converted, otherwise you may as well just get the date in ISO8601 format and append "T14:00:00Z" to it.
I think the question asks how to convert UTC to PST time (as indicated on the title). I'm making assumption that the local time is in pacific time (i.e. the server or local web browser etc)
if that's the case, in order to convert UTC time to local PST just do this
// Create date object from datetime (Assume this is the UTC /GMT) time
var date = new Date('Tue, 21 Apr 2020 09:20:30 GMT');
// Covert to local PST datetime, AGAIN this only works if the server/browser is in PST
date.toString();
I believe you can simply add 14 hours before converting to UTC.
Or you can create a new Date object out of the UTC string:
var date = new Date();
date = date.addHours(14);
var dateUTC = new Date(date.toUTCString());
I'm using moment.js 1.7.0 to try and compare today's date with another date but the diff function is saying they are 1 day apart for some reason.
code:
var releaseDate = moment("2012-09-25");
var now = moment(); //Today is 2012-09-25, same as releaseDate
console.log("RELEASE: " + releaseDate.format("YYYY-MM-DD"));
console.log("NOW: " + now.format("YYYY-MM-DD"));
console.log("DIFF: " + now.diff(releaseDate, 'days'));
console:
RELEASE: 2012-09-25
NOW: 2012-09-25
DIFF: 1
Ideas?
Based on the documentation (and brief testing), moment.js creates wrappers around date objects. The statement:
var now = moment();
creates a "moment" object that at its heart has a new Date object created as if by new Date(), so hours, minutes and seconds will be set to the current time.
The statement:
var releaseDate = moment("2012-09-25");
creates a moment object that at its heart has a new Date object created as if by new Date(2012, 8, 25) where the hours, minutes and seconds will all be set to zero for the local time zone.
moment.diff returns a value based on a the rounded difference in ms between the two dates. To see the full value, pass true as the third parameter:
now.diff(releaseDate, 'days', true)
------------------------------^
So it will depend on the time of day when the code is run and the local time zone whether now.diff(releaseDate, 'days') is zero or one, even when run on the same local date.
If you want to compare just dates, then use:
var now = moment().startOf('day');
which will set the time to 00:00:00 in the local time zone.
RobG's answer is correct for the question, so this answer is just for those searching how to compare dates in momentjs.
I attempted to use startOf('day') like mentioned above:
var compare = moment(dateA).startOf('day') === moment(dateB).startOf('day');
This did not work for me.
I had to use isSame:
var compare = moment(dateA).isSame(dateB, 'day');