I want to do a straight conversion of a date string and cannot get the results I expect. I expect the below code to produce a date equal to the date portion of the original string, but it seems to apply a time during the instance creation.
var usageTime = new Date('2012-01-19T22:59:50-0800');
console.log(usageTime); // Fri, 20 Jan 2012 06:59:50 GMT
dayOfUsage = usageTime.getFullYear()+'-'+(usageTime.getMonth()+1)+'-'+usageTime.getDate();
console.log(dayOfUsage); // 2012-1-20
I expect a date of 2012-1-19. What is the right way to solve this?
You should use getUTC*() functions (getUTCDate(), getUTCHours() and so on) to get your times with no timezone offset.
Related
I have a very simple SQL string that brings a Date field from sql:
SELECT dbo.table.effDate from table where.....
I need to convert that date to a date variable at Node so I can perform a calculation. This date is always the first of a month, so my results at SQL are
2023-01-01
2022-05-01
2022-08-01
etc.
So, when I try to convert the field to a node date type, in these different ways, I always get the previous date of the one at the field (for the example above)
2022-12-31
2022-04-30
2022-07-31
Im using:
let effDate = moment(response[i].effDate, 'YYYY-MM-DD').format('YYYY-MM-DD')
Then
let effDate = new Date(response[i].effDate)
even this is bringing me a previous date
let effDate = response[I].effDate.toString()
and this:
let effDate = new Date(response[I].effDate).toLocaleDateString('en-US')
I could fix this by adding one day to whatever SQL brings me back, but its not the point, I want to do it right.
I also tried using getTimezoneOffset
effDate = new Date(response[i].effdate.getTime() - response[i].effdate.getTimezoneOffset() * 60000)
But I always get the previous date.
What confuses me is that javascript UTC zones should have nothing to do when it comes to the value returned by SQL:
Again, I could just add a day but that wont be right, and I would like to know why this is happening (even using toString()).
Thanks.
Basically Date treats strings as being the UTC representation of that moment in time (because its the standard format to save a date in a database). Running the following line should give you a better understanding of this:
console.log(new Date('2023-01-01').toString())
I get:
Sat Dec 31 2022 16:00:00 GMT-0800 (Pacific Standard Time)
Either allow moment.js to interpret the string directly, or use the .utc() method.
// moment from Date object is still UTC, outputs local
console.log('A:', moment(new Date('2023-01-01')).format('YYYY-MM-DD'))
// moment parses string assumming local
console.log('B:', moment('2023-01-01').format('YYYY-MM-DD'))
// use moment.utc() method to keep output UTC
console.log('C:', moment(new Date('2023-01-01')).utc().format('YYYY-MM-DD'))
console.log('D:', moment.utc(new Date('2023-01-01')).format('YYYY-MM-DD'))
console.log('E:', moment.utc('2023-01-01').format('YYYY-MM-DD'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
The server uses +03:00 timezone. It offers me a date in this format: "2017-04-12T00:00:00+03:00"
I then create a new Date from this string:
options.startDate = new Date("2017-04-12T00:00:00+03:00")
But because on the client there is a different timezone, the result is actually:
Tue Apr 11 2017 23:00:00 GMT+0200 (Central Europe Daylight Time)
This brings me back one day and it's a big deal for me. Is there an elegant way to avoid this and create the same Date and Time in javascript, ignoring the timezone offset?
The date you have in options.startDate is the correct one. What you want is to display it as if you were from the same timezone as the server.
If you now server's timezone in the client script then I would considere using a library like moment.js. It would allow you to format date in the timezone you want (GMT for instance, or the one of the server).
Using both moment.js and its plugin timezone code could be :
moment("2017-04-12T00:00:00+03:00").tz("America/Los_Angeles").format();
You should never use the Date constructor or Date.parse to parse strings due to browsers differences. Even if you remove the timezone from the string and parse the remainder, e.g.
console.log( new Date('2017-04-12T00:00:00+03:00'.substr(0,19)).toString() );
you'll get different results in different browsers (e.g. Firefox and Safari).
If you don't want to use a library, use a simple function (see below). However, if you remove the timezone, the string will represent a different moment in time in each timezone with a different offset.
function parseISOIgnoreTimezone(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2], b[3], b[4], b[5]);
}
console.log(parseISOIgnoreTimezone('2017-04-12T00:00:00+03:00').toString());
I really recommend #VictorDrouin his answer.
But if for some reason you don't want moment.js or fiddle around with it you can use this 'hack'
new Date("2017-04-12T00:00:00+03:00".match(/\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}/).pop());
What it does it matches the date against given regex date format, and then supplies it to the date parser which makes it a date.
Be careful when supplying it back to the database that you supply it back without timezone offset.
var stringdate = "2017-04-12T00:00:00+03:00";
function getDate(str_date) {
var matched = str_date.match(/\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}/).pop();
return new Date(matched);
}
console.log(getDate(stringdate));
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.
Need help to convert exactly from ISO Date string to Date:
I have an ISO string date: "2016-01-23T22:23:32.927".
But when I use new Date(dateString) to convert Date, the result is wrong:
var date = new Date("2016-01-23T22:23:32.927");
The result is: Sun Jan 24 2016 05:23:32 GMT+0700. It's not true. I want the date is 23 not 24.
Please help me. Thanks a lot!
You need to supply a timezone offset with your iso date. Since there isn't one, it assumes the date to be in GMT and when you log it out, it prints it in the timezone of your browser. I think that if you pass "2016-01-23T22:23:32.927+07:00" to new Date() you would get the value you are expecting.
JavaScript environments (browser, node,...) use a single timezone for formatting dates as strings. Usually this is your system's timezone. Based on the output you get, yours is GMT+0700.
So what happened:
The string you passed as ISO format to the Date constructor doesn't specify a timezone. In this case it is treated as UTC.
When you then output the date (I'll assume with console.log), it is converted to the timezone of your environment. In this case 7 hours where added.
If that doesn't suit you, you can change the way you output the date. This depends on what output you want, e.g.:
If you just want the UTC timezone again, you can use date.toISOString().
If you want to output it in another timezone, you can call date.getTimezoneOffset() and figure out the difference between both timezones. You'd then probably need to get the individual date parts and add/subtract the timezone difference accordingly. At this point you could consider using an existing library, taking into account their possible disadvantages.
If you're willing and able to add a dependency, I recommend using moment.js for this. It makes date handling in Javascript much more straightforward and a lot safer, and fixes your specific problem right out of the box.
To do this, 1st load it from a CDN, e.g. Moment.JS 2.14.1 minified. Then use it as follows:
var date = moment("2016-01-23T22:23:32.927");
console.log(date);
// output: Sat Jan 23 2016 22:23:32 GMT-0500
...i.e. your desired result :)
Here's a jsfiddle demonstrating this.
Use date.toUTCString()
it'll give you 23 instead of 24 as it Convert a date object to a string, according to universal time
Because of how we store dates I need to set a moment object to timezone +0000.
I've tried using a variety of ways:
var d = moment().hour(0).minute(0).second(0).millisecond(0).zone('+0000');
var d = moment().hour(0).minute(0).second(0).millisecond(0).utc(0);
var d = moment().hour(0).minute(0).second(0).millisecond(0).utc();
When I console.log these dates they come out with the time 00:00:00 GMT+0100 (BST)
Looking at the documentation it seems to say that .utc() and .zone() are for printing a format only, is this true? (This is the same I've seen with other questions on here, none address setting the actual object to a timezone it seems)
After I set and then manipulate the date I convert it to the JS Date object to use with angular-ui bootstrap datepicker (note: it was a moment object which I used console.log on).
Unless you specify a timezone offset, parsing a string will create a
date in the current timezone.
http://momentjs.com/docs/#/parsing/string-format/
Example: You can tell in which timezone is your date using
moment ('2015-05-06T23:00:00.000Z').
If you need to convert this to a specific timezone you can do so:
moment().utc(0).format('YYYY-MM-DD HH:mm Z').
About Timezone in Javascript: How do I specify the time zone when creating a JavaScript Date?