I've been playing around with the Date() object while studying when I noticed that setUTCHours() returns the wrong day.
Example:
var myDate = new Date(2014, 0, 1);
myDate.setUTCHours(10);
myDate;
Looking at this, I expected the date to be Wed Jan 01 2014 10:00:00 UTC, but instead Its one day behind. Why is that?
Here's my http://jsfiddle.net/L5QEC/ with comparisons to some other basic methods.
Date objects use a time value that is UTC. They also have an offset that represents the timezone offset of the host system. By default, dates and times will use the offset to display local values. If you are UTC+1, then the offset will be -60 and new Date(2014, 0, 1) will create a date for 2013-12-31T23:00:00Z and use the offset to display a local date of 2014-01-01T00:00:00+0100.
So if you change the UTC hours to 10, the UTC time is: 2013-12-31T10:00:00Z and the local equivalent is 2013-12-31T11:00:00+0100.
So by setting the UTC hours to 10 you effectively set the local time to 11:00 (i.e. the UTC hours + 1 hour offset) on the previous day.
If you'd like to set a specific date and time in UTC, consider:
var dt = new Date(Date.UTC(2014, 0, 1, 10, 0, 0));
The result will represent that point in universal time, but you will see it adjusted to the local time zone for display. For example:
"Wed Jan 01 2014 02:00:00 GMT-0800 (Pacific Standard Time)"
Read the UTC date, not the local (default) Date:
var myDate = new Date(2014, 0, 1);
myDate.setUTCHours(10);
myDate.toUTCString();
One dirty way is to convert the local date to UTC before you use setUTCHours
function UTCDate() {
var dateObject = new Date();
var UTC = new Date(dateObject.getUTCFullYear(),
dateObject.getUTCMonth(), dateObject.getUTCDate(),
dateObject.getUTCHours(), dateObject.getUTCMinutes(),
dateObject.getUTCSeconds(),dateObject.getUTCMilliseconds());
return UTC;
}
When the time is 0 hours and 0 minutes, there's this annoying one-day delay based on the GMT.
For example if the GMT is +2, the number of hours of the date must be greater than 2 otherwise the date takes one day less.
The solution I found to avoid this weird effect is to use this trick.
var myDate = new Date(2014, 0, 1);
var timezoneOffset = myDate.getTimezoneOffset();
if (timezoneOffset > 0) {
myDate.setMinutes((24 * 60) - (timezoneOffset + 1));
} else {
myDate.setMinutes(-timezoneOffset); // Do not forget the negative sign !
}
myDate.setUTCHours(10);
So when I add the time corresponding to the GMT offset I no longer have this wrong date !
I tested all GMTs by changing the settings of my operating system (-13, -2, +2, +12)
You can set the UTCMinutes after that if you want !
The getTimezoneOffset() method returns the time difference between UTC time and local time, in minutes.
For example, If your time zone is GMT+2, -120 will be returned.
Related
I have a GMT+1 date object Wed Feb 01 2017 00:00:00 GMT+0100 (CET). I want to convert this object to GMT+0 with exactly the same date:
GMT: 1 Feb 2017 00:00:00 GMT;
When I parse my object it returns timestamp which is equal to Tue, 31 Jan 2017 23:00:00 GMT.
How to convert my GMT+1 date object to gets timestamp equal to the same date in GMT+0? I tried to use moment.js but I couldn't handle that.
#edit
code with explanation here
// User chooses 1st Feb 2017, but since components works with GMT +1
const userChoice = new Date(2017, 01, 01, 0, 0, 0)
// And backend works with timestamps I parse userChoice
const timestamp = moment(userChoice).valueOf()
// Which gives me timestamp equal to 31st of Dec 2016
console.log(timestamp, moment(timestamp).utc().format('DD/MM/YYYY hh:mm:ss Z'))
// But I want to have the same date as user chooses, but in a specific (GMT+0) timezone
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Ok, I found out the solution. We will call date object "mod" which gives us Wed Feb 01 2017 00:00:00 GMT+0100.
const mod = new Date(1485903600000)
Now we will create variable that gives us timestamp of the exact same time (e.g. day, hours, etc.) but in UTC.
const utc = Date.UTC(mod.getFullYear(), mod.getMonth(), mod.getDate(), mod.getHours(), mod.getMinutes(), mod.getSeconds())
If we want to check if our timestamp is correct we can simply create new Date with this timestamp and console.log it.
console.log(1485907200000) // Wed Feb 01 2017 01:00:00 GMT+0100 <=> Wed Feb 01 2017 00:00:00 GMT+0000
It's not clear to me what you are trying to do. Looking at your code:
// User chooses 1st Feb 2017, but since components works with GMT +1
const userChoice = new Date(2017, 01, 01, 0, 0, 0)
That creates a Date object equivalent to midnight at the start of 1 February 2017 in the host system time zone.
// And backend works with timestamps I parse userChoice
const timestamp = moment(userChoice).valueOf()
You aren't "parsing" userChoice, it's a Date object. You're getting the time value, which is an offset in milliseconds since 1970-01-01T00:00:00Z and is equivalent to userChoice.getTIme().
// Which gives me timestamp equal to 31st of Dec 2016
console.log(timestamp, moment(timestamp).utc().format('DD/MM/YYYY hh:mm:ss Z'))
No it doesn't. The original date is for 1 Feb, it can only be shifted by a maximum of one day either way by time zones. For hosts set to a timezone west of Greenwich, the timezone adjustment when the Date is created will mean the UTC date is 1 Feb, but for hosts to the east, the UTC date will be 31 Jan.
// But I want to have the same date as user chooses, but in a specific (GMT+0) timezone
To create a Date for a specific UTC date, then use UTC methods. Alternatively, if you have a Date object, you can adjust it by the host offset:
// Create date for 1 Feb, 2017 based on host offset
var d = new Date(2017, 1, 1);
// Create UTC Date for same date
var u = new Date(Date.UTC(2017,1,1));
console.log('Local: ' + d.toISOString());
console.log('UTC : ' + u.toISOString());
// Adjust d for timezone offset
d.setMinutes(d.getMinutes() - d.getTimezoneOffset())
console.log('Adjusted: ' + d.toISOString());
If that doesn't help, please update the question.
A date object can not be converted to different time-zone as it only keeps the number of milliseconds that passed since Jan 1, 1970 and it is the same for all places around the world.
However the date object may be interpreted in different time zone (also known as a local time) based on the time-zone offset value.
You do not need to even know the fixed value of the time-zone offset;
let the computer take care of it for you, as it will also include summer daylight saving time changes between different places and at the right time.
All you need to know is the time-zone description that could be looked-up at iana.org website.
let now = new Date(),
current = Intl.DateTimeFormat().resolvedOptions().timeZone,
zones = [current , 'Europe/London', 'Asia/Tokyo'];
zones.forEach((z)=>{
console.log("Time in "+ z + " is " +
now.toLocaleString("en-ES",{timeZone: z}))
});
I've got a UTC timestamp in milliseconds.
It represents 16:00 on a certain day in GMT time.
timestamp: 1450281600000
I want to modify only the hours, minutes component portion of this value and return the new value.
For example 16:30 is 59400000 but it doesn't have the days and year.
How do I correctly change the utc stamp?
I'm programming in Javascript.
Throw your timestamp into a Date object, manipulate it with the date functions, and then use valueOf to return a timestamp again.
var d = new Date(1450281600000);
d.setHours(1);
d.setMinutes(30);
alert(d.valueOf()); // 1450247400000
You'd want to use standard Date object.
For example, to change 16:00 to 16:30 of that day, you'd do like this:
dt = new Date(1450281600000); // instatiates Date from timestamp
// Wed Dec 16 2015 17:00:00 GMT+0100 (CET) in my local representation
dt.getMinutes(); // will return 0
dt.setMinutes(30);
// dt now is represented as 1450283400000 timestamp...
dt.getTime(); // ...which you can see here.
I am trying to add 3 months to today's date in a javascript. This is my code:
var now = new Date();
now.setHours(0, 0, 0, 0);;
now.setMinutes(0);
var plus3mo = new Date();
plus3mo.setMonth((now.getMonth() + 3));
plus3mo.setHours(0, 0, 0, 0);
plus3mo.setMinutes(0);
var utc_timestamp_today = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
var utc_timestamp_3moFromNow = Date.UTC(plus3mo.getFullYear(), plus3mo.getMonth(), plus3mo.getDate(), 0, 0, 0, 0);
I want to add exactly 3 months to today's date and have the hours. It is doing that, but the catch is I need the hours to be set to exactly 00 hours or 12am. I am getting weird results with the code I have.
Here are my results that I viewed while debugging and using this UTC time stamp converter site.
1441929600000 --> 09/10/2015 20:00:00 ("Today's Date")
1449792000000 --> 12/10/2015 19:00:00 ("3 Months From Now")
As you can see, I am adding 3 months, but the hours are centered at 8pm and 7pm. Why is this happening?
Using date manipulation in JS always gives you a date relative to the local time of the browser. So using
var now = new Date();
now.setHours(0, 0, 0, 0);
now.setMinutes(0);
Will give you a date in now that is at midnight for your local time, but is at your local timezone offset relative to UTC. (I assume this is currently +4 hours currently and changes to +5hours) when daylight savings kicks in for the winter.
In order to get midnight UTC for each date, I'd suggest:
getting the UTC date timestamp from each Date using getTime/valueOf
determining the offest using getTimezoneOffset
convert the offset from minutes to milliseconds (multiply by 60000) and subtract from the original timestamp
use setTime on each date object if you need the Date objects in their original locale but at midnight UTC
Why is it when I have
var dt = new Date(2015, 6, 1);
dt.toUTCString()
My output is Tue, 30 Jun 2015 23:00:00 GMT
And
var dt = new Date(2015, 6, 2);
dt.toUTCString()
Wed, 01 Jul 2015 23:00:00 GMT
I'm clearly missing something here, I want to be able to loop through each days of the month and get a Date() for that day
I don't understand why if the day is 1, it says the date is the 30th
Javascript dates are always generated with local time zone. Using toUTCString converts the time in the Date object to UTC time, and apparently in your case that means -1 hours. If you want to initialize a Date object with UTC time, use:
var dt = new Date(Date.UTC(2015, 6, 1));
The toUTCString() method converts a Date object to a string, according to universal time.
The Universal Coordinated Time (UTC) is the time set by the World Time Standard.
Note: UTC time is the same as GMT time.
Try to change dt.toUTCString() in another function.
There are a lot of hour on the planet,for example in America is the 5 o' Clock,in Japan is 10 o' Clock etc... the UTC is a time zone,try to change this.
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());