I am using a jQuery UI datepicker to show a range of dates that are available to the user. I get the date ranges from an API in the form of
"DateRanges": [
{
"StartDate": "0001-01-01T00:00:00",
"EndDate": "0001-01-01T00:00:00"
}
]
The problem is that I am running a comparison on the dates in the beforeShowDay API mapping function, but when I try to convert these dates into a JavaScript Date object for comparison, the Date() constructor is converting the dates to local time and therefore causing the date to change.
For example, if I use new Date("2014-08-22"); then I would expect a Date object that was set to 8/22/2014 at 12:00 AM but instead it is showing 8/21/2014 at 5:00 PM PST. Therefore my comparison does not work correctly because of the conversion.
What can I do to force the Date() object to not change to local time when making comparisons?
This happens because the parsing logic defaults to the UTC time zone when you do not supply one. To get the expected time, pass a time zone.
new Date("2014-08-22T00:00:00-0700");
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
This is another tidbit from the docs that might help (depending on how you are generating those dates):
Given a date string of "March 7, 2014", parse assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC. Therefore Date objects produced using those strings will represent different moments in time unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted (this behavior is changed in ECMAScript ed 6 so that both will be treated as local).
so you could also use:
new Date("September 11, 2014");
and you will get a date in your local tz (for me the output is: "Thu Sep 11 2014 00:00:00 GMT-0500 (CDT)").
Related
my system uses timezone UTC+03:00 ,
im trying to get a date in string format, represented by NY timezone,
and convert it to a Date object in utc
const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York")
.tz("Z").toDate();
doesnt work correctly
how am i even suppose to convert to utc time?
-----------edit---------------
i got it to work, using the timezone "Africa/Accra" , where UTC offset is 0, and ther is no daylight savings time:
moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York").tz("Africa/Accra")
but this solution is a bad workaround, and if the government of Accra decide to change the time laws, will stop working!
is there a way to set the utc offset to 0 in momentjs-timezones?
As Álvaro González mentioned, that Date object does not contain Time zone information.
I do the following:
new Date(moment.tz(date, currentTimezone).tz(newTimezone).format('YYYY/MM/DD HH:mm:ss'))
where date is a date object or a string (e.g. '2017-10-30 16:30:00.0000')
so, I change date from currentTimezone to newTimezone and after that new Date object will be returned
Let's change '2017-10-30 16:30:00.0000' from UTC to America/Toronto (UTC-4)
new Date(moment.tz(date, 'UTC').tz('America/Toronto').format('YYYY/MM/DD HH:mm:ss'))
And I got
Mon Oct 30 2017 12:30:00 GMT+0400
GMT+0400 is my timezone and console.log() just shows it with any
date object and it can mislead you. Please, don't look at the this
timezone.
Let's change '2017-10-30 16:30:00.0000' from Europe/Samara (UTC+4) to America/Toronto (UTC-4)
new Date(moment.tz('2017-10-30 16:30:00.0000', 'Europe/Samara').tz('America/Toronto').format('YYYY/MM/DD HH:mm:ss'))
Firstly, moment.tz undertands that date has no timezone information and associate with Europe/Samara (UTC+4)
timezone. After that computes difference between new and old
timezone (it's -8 hours in this case)
And returns result
Mon Oct 30 2017 08:30:00 GMT+0400
And answer on your question
If xsltDate is a date object or string which do not contain timezone information
dateUTC = new Date(moment.tz(xlsxDate, "America/New_York").tz("UTC").format('YYYY/MM/DD HH:mm:ss'));
If xsltDate contain timezone information (e.g.'2013-06-01T00:00:00-04:00'), then no need to tell moment.tz which timezone xlsxDate has, just mention a new timezone
dateUTC = new Date(moment.tz(xlsxDate, "UTC").format('YYYY/MM/DD HH:mm:ss'));
Short answer is that you cannot.
The .toDate() method of the Moment library returns a native Date object. Such objects do not keep memory of any specific time zone (that's one of the reasons to use Moment in the first place), they just keep track of the exact time moment represented and merely pick a time zone when formatting to string, which is either UTC or the browser's time zone (not an arbitrary one).
The long answer is that you're probably getting correct results but are printing them with a method that uses the browser's time zone.
i found a function that does what i was trying to do, it belongs to the momentjs library itself: utcOffset(n) sets the offset to n.
(i also had to explicitly write the date string format correctly, thanks VincenzoC)
this is the code i was trying to write:
const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York");
const dateUTC = dateInNY.utcOffset(0).toDate();
however, the toDate function changes the timezone to my local timezone anyway, so .utcOffset(0) is redundat, and i can just use moment this way:
const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York");
const dateUTC = dateInNY.toDate();
and change the Date objects date to utc time later (in my case, the JSON.stringify stuff i use later does that for me)
I have dates stored in my database in UTC format and calling
element.createdDate = new Date(element.createdDate.toString());
results in displaying the wrong date.
calling
element.createdDate = new Date(element.createdDate.toUTCString());
returns nothing. How do I go about displaying the correct time from UTC?
It appears that your json response contains a string valued which are in ISO8601 format in UTC, and then you are creating Date objects from them.
This part of your code is fine:
if (element.createdDate) element.createdDate = new Date(element.createdDate.toString());
You parse the string, and the resulting Date object is correct.
However, you don't need to use .toString() here, as the value is already a string. That is redundant.
This part of your code is the problem:
console.log("javascript date: " + new Date(element.depositDate.getUTCDate().toString()));
The getUTCDate function returns just the date of the month. Don't use that.
No matter what you do to create the Date object, ultimately you create a Date object and you're relying upon an implicit string conversion to output it. This will have different behavior in different browsers.
Consider console.log(new Date()):
In Chrome, this logs something like Fri Mar 17 2017 12:14:29 GMT-0700 (Pacific Daylight Time) on my computer. This is as if I called console.log(new Date().toString()); It is in an RFC 2822 like format (but not quite), and is represented in local time.
In Firefox, this logs something like 2017-03-17T19:14:46.535Z. This is as if I called console.log(new Date().toISOString()); It is in ISO8601 format, and is represented in UTC.
The point is, don't rely on implicit undefined behavior. If you must work with Date objects, then you should use console.log(element.createdDate.toISOString()) to see the ISO8601 representation of the UTC time.
If you're going to be doing a lot of things with dates and times, you may prefer to use a library, such as Moment.js, which can make tasks such as this more clear.
I have dates stored in my database in UTC format and calling
element.createdDate = new Date(element.createdDate.toString());
results in displaying the wrong date.
2016-10-11T00:00:00Z and Mon Oct 10 2016 20:00:00 GMT-04:00 (EDT) are exactly the same moment in time. The only difference is that one is displayed in ISO 8601 extended format with timezone offset 00:00 and the other is displayed in an RFC 2822 (like) format with timezone offset -04:00 (and assumes a locality in the EDT region).
calling
element.createdDate = new Date(element.createdDate.toUTCString());
returns nothing.
That is unusual. Typically it would return either a string or an error, but without a working example or any code to provide context it's impossible to say why.
How do I go about displaying the correct time from UTC?
You haven't specified what "correct" is. You are displaying a date and time for the same moment in time, just in a different format and time zone.
I'm trying to compare two dates in javascript which are formatted differently. Namely:
2015-09-30T00:00:00 and 9/30/2015 12:00:00 AM
The former is UTC and the latter is not in UTC format. Logically, I am referring to the same date/time here but I can't come up with a way to compare them that will return true. Creating a new Date object with each ends up with different results (due to UTC offset with my local time zone).
What am I missing?
Ended up concluding that tagging on a "UTC" to the second date format before creating the Date object leads to an output consistent with the UTC formatted date.
I want to take date in my module with JSON format and when I am converting my date value to json then it changes the timezone ultimately date gets change for eg
var myDateWithJson=(new Date(2014, 03, 11).toJSON());
alert("Date With Json " +myDateWithJson);
var myDateWithoutJson = new Date(2014,03,11);
alert("Date Without Json " + myDateWithoutJson);
I also gone through covert json without timezone but, I don't think that is better approch
Please guide me for the better approch
In your code:
var myDateWithJson=(new Date(2014, 03, 11).toJSON());
will create a date object for 00:00:00 on the morning of 11 April 2014 (note that months are zero indexed here) in your current locale based on system settings. Calling toJSON returns an ISO 8601 date and time string for the equivalent moment based on UTC.
The date object will have an internal time value that is milliseconds since 1970-01-01T00:00:00Z.
var myDateWithoutJson = new Date(2014,03,11);
That creates a date object for exactly the same moment in time, i.e. with exactly the same time value.
alert("Date Without Json " + myDateWithoutJson);
That calls the toString method of the date object that returns a human readable string representing the date and time in the current locale based on system settings.
So the first is a UTC string, the second is a local string. Both represent the exact same instant in time, and, if converted back to Date objects, will have exactly the same internal time value.
So I have iso date time that need to be converted from a string to date object. How do I keep date from converting it to local browser timezone.
new Date('2013-07-18T17:00:00-05:00')
Thu Jul 18 2013 18:00:00 GMT-0400 (EDT)
I want to get
Thu Jul 18 2013 17:00:00 GMT-0500 (XX)
While MomentJS is a great library, it may not provide a solution for every use case. For example, my server provides dates in UTC, and when the time portion of the date is not saved in the db (because it's irrelevant), the client receives a string that has a default time of all zeros - midnight - and ends with an offset of +0000. The browser then automatically adjusts for my local time zone and pulls the time back by a few hours, resulting in the previous day.
This is true with MomentJs as well.
One solution is to slice off the time portion of the string, and then use MomentJS as described in the other answers.
But what happens if MomentJS is not a viable option, i.e. I already have many places that use a JS Date and don't want to update so many lines of code? The question is how to stop the browser from converting dates based on local time zone in the first place. And the answer is, when the date is in ISO format, you cannot.
However, there is no rule that says the string you pass to JavaScript's Date constructor must be in ISO format. If you simply replace the - that separates the year, month, and day with a /, your browser will not perform any conversion.
In my case, I simply changed the format of the Dates server-side, and the problem was solved without having to update all the client-side JS dates with MomentJS.
Note that the MDN docs for JavaScript's Date class warn about unpredictable browser-behavior when parsing a string to create a Date instance.
You cannot change this behavior of Javascript because it is the only simple way for Javascript to work. What happens is simply that Javascript looks at the time shift, computes the matching timestamp, and then asks the OS for the representation of this timestamp in the local time zone. What is key to understand here is that -05:00 is not an indication of time zone but simply a shift from UTC.
Time zones are complex beasts that are just arbitrary political decisions. The OS provides a service to display time in the local time zone, but not in other time zones. To do that you have to take in account things like DST that are pretty much a hell.
As always with time management, the only decent way to tackle this problem is to use a dedicated library. In Javascript, you'll find Moment.js and Moment.Timezone.js very helpful.
Example http://codepen.io/Xowap/pen/XKpKZb?editors=0010
document.write(moment('2013-07-18T17:00:00-05:00').tz('America/New_York').format('LLL'));
As a bonus, you get a ton of formatting/parsing features from Moment.js.
Please also note that as long as you use the ISO 8601, your date can be pinpointed to a precise moment, and thus be displayed in any timezone of your liking. In other words, JS "converting" your date doesn't matter.
You can use a library such as Moment.js to do this.
See the String + Format parsing.
http://momentjs.com/docs/#/parsing/string-format/
The following should parse your date you provided, but you may need to modify it for your needs.
var dateString = "2013-07-18T17:00:00-05:00";
var dateObject = moment(dateString, "YYYY-MM-DDTHH:mm:ssZ").toDate();
Alternatively, see Moment's String parser, which looks like it is in the format you provided, with the exception of a space between the seconds of the time and the time zone.
http://momentjs.com/docs/#/parsing/string/
This is an old question that recently got linked in an answer to a newer question, but none of the existing answers seem to fully address the original question.
In many cases the easiest way to format and display a datetime string in the time zone that it is received, is not to convert the string to a Date object at all. Instead, just parse the datetime string and recombine the parts into the desired format. For example, if you can live without the day of the week in the output requested in the question, you could do something like the following to handle the requested input and output format (including the day of the week adds enough complexity that it might be worth using a library at that point). Of course, this approach requires modification based on the format of the datetime strings you are receiving on the client side.
const months = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'};
const format = (datetime) => {
const [date, time] = datetime.split('T');
const [y, m, d] = date.match(/\d+/g);
const [t, tz] = time.split(/(?=[+-])/);
return `${months[Number(m)]} ${d} ${y} ${t} GMT${tz}`;
};
const dt = format('2013-07-18T17:00:00-05:00');
console.log(dt);
// Jul 18 2013 17:00:00 GMT-05:00
There are JavaScript and other library methods that will allow you to convert your datetime string to a Date instance and then display it in a specific time zone if you are consistently receiving datetime strings from one or a few specific time zones that are easily identified on the client side. Following are a couple of examples.
toLocaleString enables you to display a date in a specific time zone but the options parameters required to set the time zone are not supported across all browsers (as of the date of this answer). For example (note that parsing of date strings with the Date constructor is still discouraged, but most modern browsers will handle an ISO 8601 format string like the one below):
const dt = new Date('2013-07-18T17:00:00-05:00');
const ny = dt.toLocaleString('en-US', { timeZone: 'America/New_York' });
console.log(`Local: ${dt}`);
console.log(`New York: ${ny}`);
You could also use Moment.js with Moment Timezone to display a date in a specific time zone. For example:
const ny = moment('2013-07-18T17:00:00-05:00').tz('America/New_York').format();
console.log(`New York: ${ny}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
It is important to note the following when working with datetime strings and time zones in JavaScript. The JavaScript Date constructor DOES NOT change the time zone offset. When you create a date from a string using ISO 8601 format as in the question example, Date does the following:
Creates a JavaScript Date instance that represents a single moment in
time. Date objects use a Unix Time Stamp, an integer value that is the
number of milliseconds since 1 January 1970 UTC.
In other words, JavaScript Date instances do not store (or change) time zone offsets. The reason you often see output from a JavaScript Date in your local time zone is that toString is the default method called when you log a Date instance to the console (or use various other approaches to output your date). In most browser implementations, this method relies on the browser's local time zone to convert the number of milliseconds since 1 January 1970 UTC into a string representation of the date.
Wonder if this would help:
function goAheadMakeMyDate(s){
var d = new Date(s);
// override Date.toString()
d.toString = function(){ return ''+s; };
return d;
}
var example = goAheadMakeMyDate("Fri 19 July 2013 12:00:00 GMT");
example.toString() // returns string actually used to construct the date
'Fri 19 July 2013 12:00:00 GMT'
example.toLocaleString()
'Fri Jul 19 2013 08:00:00 GMT-0400 (EDT)'
1*example // gives seconds since epoch
1374235200000
With your input:
example = goAheadMakeMyDate('2013-07-18T17:00:00-05:00')
{ Thu, 18 Jul 2013 22:00:00 GMT toString: [Function] }
> example.toString()
'2013-07-18T17:00:00-05:00'
> example.toLocaleString() // I live in GMT-4
'Thu Jul 18 2013 18:00:00 GMT-0400 (EDT)'
> 1*example // convert to integer date
1374184800000
However, if you start modifying this date, the toString will not change and will bite you.
I have a scenario where date time stamp needs to update only once. In detail I have button in my application and when clicked on it will generate a PDF along with timestamp footer and when refreshed it should not change date time.
For the above scenario I have used localStorage.setItem('','') and getItems. In precise.... when clicked on generate button I have used localStorage.setItem('','') and in the generating footer logic I have used localStorage.getItem('') dats it....
Explanation for above logic:
Whenever we are generating I am setting current date time and when generating am calling getItem which will pick the set date time from local storage.
This will reset again when clicked on Generate button.
Hope this helps someone in need..... :-)