I've seen various versions of this question, but none of them answer my needs.
I want to create an ISODate for MongoDB and I'm using Node.js.
In Node, when I do:
console.log(Date());
I get:
Mon Sep 26 2016 15:17:04 GMT-0400 (EDT) <-- This is correct.
When I do:
console.log(new Date());
I get:
2016-09-26T19:17:04.731Z <- This is 4 hours ahead
My understanding of the way to do ISODATE is:
var isodate = new Date().toISOString()
console.log(isodate);
Which yields a time 4 hours ahead of "now".
My system date is correct.
I run this one different machines, and I get the same results.
Can someone please explain why I'm getting a discrepancy in time?
The difference is that 2016-09-26T19:17:04.731Z related to GMT0 timezone and Mon Sep 26 2016 15:17:04 GMT-0400 (EDT) to your local timezone. Both are point to the same time :)
You can read more about data formats and timezones in Wiki
With a basic definition to the difference between Date() and new Date()
is :
Date() ignores any argument(s) passed to it and is equivalent of new Date().toISOstring()
new Date(Optional_arguments) creates an time type object in JS on which you can perform :
getTime()
other Date.prototype functions listed on MDN Website
Date() is just a string representation of local time.
new Date() gives you a manipulatable object to fiddle around.
Notice the Z at the end of 2016-09-26T19:17:04.731Z?
It stands for Zulu, meaning UTC timezone (which is GMT+000).
As you can see in your original date string, Mon Sep 26 2016 15:17:04 GMT-0400 (EDT) has a GMT-0400 timezone, which I guess is the local time where you live.
So, in fact there is no problem, just different representations of the same time:
Date() creates a Local date
new Date() creates a UTC date
Related
app.get("/test",function(req,res){
var d = new Date();
res.send(d);
});
This give output "2019-03-19T04:50:47.710Z" which is UTC when i visit through mydomain/test
app.get("/testejs",function(req,res){
res.render("testejs");});
My testejs below-
<%= new Date() %>
This ejs when visited through mydomain/testejs gives output -
Tue Mar 19 2019 12:55:52 GMT+0800 (Singapore Standard Time)
How is this possible that new Date() give me two different output from( app.js and testejs.ejs ) but it is executed on same server?
new Date().toLocaleString()
Click here Out put is there
OR
new Date(Date.now()).toLocaleString()
Sample Out Put nodejs backend and frontend ejs using date function 3/19/2019, 10:58:31 AM
Good day,
Remember that app.js is running on the server side and ejs on the browser, the browser date format is different from the server.
new Date() generates a date value, which is a number of milliseconds since a base time, usually Jan 1, 1970. The exact value depends on the setting of the clock on the server where the value is generated.
That value can be displayed in various ways.
Depending on the default settings of the client environment,
that my be in UTC, or the local [or some other] time zone,
and in various formats.
Note that 04:50 UTC and 12:55 GMT+0800 are about 5 minutes apart,
but in different time zones. If this was two tests run 5 minutes
apart, that would explain the difference.
Instead of using the default toString() method to display the times,
use getTime() to see what the raw number is.
They both are not two different dates but the same date in different timezones.
Reason for the different format is how the toString() method is written for the Date object,
the toString() method is written in a way to return the UTC formatted date so when you send it on the browser it calls the toString for the date as everything will be converted into a string before mounting.
new Date() invokes the constructor and return the date instance which also will have all its methods, however, Date() is a function which returns the stringified date.
See the examples below
date = new Date('Tue Mar 19 2019 12:55:52 GMT+0800')
console.log(date)
console.log('toString-%s',date.toString())
console.log('toString-%s',''+date)
console.log('Tue Mar 19 2019 12:55:52 GMT+0800')
//Managing offsets
console.log(Date('Tue Mar 19 2019 12:55:52 GMT+0800'))
date.setTime(date.getTime() + (8-5.5)*60*1000 );
console.log(date)
Given I have the number 1446309338000, how do I create a JavaScript UTC date?
new Date(1446309338000) will equal a CST time (central standard) or local time.
new Date(Date.UTC(year, month, day, hour, minute, second)) haven't got this info yet.
Does JavaScript change the time if I do this?
new Date(1446309338000).ISOString();
Is it creating a new CST date and then converting it to UTC? I really just need the string. I am taking it from a database (RowKey from a Azure Table storage database).
If you have the milliseconds that's already the UTC date. Which basically means the universal time. Now based on those millis you can convert the Date object into a String of your like:
new Date(1446309338000).toUTCString() // timezone free universal format
> "Sat, 31 Oct 2015 16:35:38 GMT"
new Date(1446309338000).toString() // browser local timezon string
> "Sat Oct 31 2015 09:35:38 GMT-0700 (PDT)"
new Date(1446309338000).toISOString() // ISO format of the UTC time
> "2015-10-31T16:35:38.000Z"
Now, if for some reason (I can't see a valid reason, but just for the heck of it) you're looking for having a different amount of milliseconds that represent a different date but that would print the same in the local browser timezone, you can do this calculation:
new Date(1446309338000 - new Date(1446309338000).getTimezoneOffset() * 60 * 1000))
Now toString from original Date and toUTCString of this new Date would read the same up to the Timezone information, because of course they're not the same date!
new Date(1446309338000).toString()
> "Sat Oct 31 2015 09:35:38 GMT-0700 (PDT)"
new Date(1446309338000 - new Date(1446309338000).getTimezoneOffset() * 60 * 1000).toUTCString()
> "Sat, 31 Oct 2015 09:35:38 GMT"
It's actually as simple as homemade biscuits, If you have your date, say:
var date_in_milliseconds = 1504640419000;
You can then initialize a new date like this:
var human_readable_date = new Date(0); //Date(0) creates a date at the Epoch, so Wed Dec 31 1969
now, just add the milliseconds to the Epoch, and this will give us the desired date:
human_readable_date.setUTCMilliseconds(date_in_milliseconds);
Well, if the date string is what you require, hope this helps:
new Date(1446309338000).toLocaleString('en-US', {timeZone: 'UTC'})
As far as toISOString() is concerned, it returns string representation using ISO-8601 standard (the format is: YYYY-MM-DDTHH:mm:ss.sssZ).
toLocaleString() is human readable format with same result.
I am trying to create a Date object in JavaScript, passing a string like this:
2014-11-30T00:00:00.0000000
However, the value of the Date object is:
Sat Nov 29 2014 17:00:00 GMT-0700 (Mountain Standard Time)
It changed it to 11/29 when I want 11/30. Is there any way I can make the date 2014-11-30, regardless of what time zone the browser is in?
Note: One possible workaround is to use the Date(year, month, day) constructor; however, I am constructing the data in a JSON string, which doesn't appear to support this.
EDIT:
Actually, I just did a test and created a date using Date(2015, 1, 1) and it gives me:
Mon Feb 02 2015 00:00:00 GMT-0700 (Mountain Standard Time)
So I can't even create a date that way and have it be the date I want. I don't understand why this is so difficult.
You can use Date.UTC
The UTC() method differs from the Date constructor in two ways.
Date.UTC() uses universal time instead of the local time.
Date.UTC() returns a time value as a number instead of creating a Date
object.
EDIT - why does SO insist on making links so hard to spot? That, up there, is a link to the docs in case that wasn't obvious.
EDIT 2 - I think I misunderstood. Try this:
var d = new Date('2014-11-30T00:00:00.0000000');
var utc = new Date(
d.getUTCFullYear(),
d.getUTCMonth(),
d.getUTCDate(),
d.getUTCHours(),
d.getUTCMinutes(),
d.getUTCSeconds()
);
alert('d: ' + d + "\n" + 'utc: ' + utc);
I have a js timestamp of Tue Sep 30 2014 12:02:50 GMT-0400 (EDT)
with .getTime() I got 1412092970.768
for most cases, its a today's specific time stamp. I wonder, if I could always ONLY pick out the day month and year and hour, min, day will be always stay with 0.
So for our situation, it should become Tue Sep 30 2014 00:00:00 GMT-0400 (EDT).
I wonder what kind of conversion should I be doing? Because seem convert to unix timestamp with getTime() will result in unknown way of calculation... and I can not really find a way to set time like I would do in PHP.
Any fix for this situation?
Thanks
You can create a date object and then zero-out any components you don't need, or create one with the components you specified, e.g.
foo = new Date();
foo.setHour(0);
foo.setMinute(0);
or something more like
foo = new Date(); // "now"
bar = new Date(foo.getYear(), foo.getMonth(), foo.getDate(), 0 , 0, 0, 0);
// create new date with just year/month/day value, and time zeroed-out.
The constructor's args are detailed here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
An other option is to send epoch to PHP:
JS:
long epoch = System.currentTimeMillis()/1000;
PHP:
$dt = new DateTime("#$epoch");
$dt->format('Y'); //year
I'm trying to convert a date string into a date object without changing the timezone. Here is the standard behavior:
new Date ("2014-10-24T00:00:00")
result
Thu Oct 23 2014 19:00:00 GMT-0500 (Central Daylight Time)
I am able to reverse the timezone by getting the offset in minutes, multiplying it by 60,000, and then adding that to the new string date.
new Date(new Date("2014-10-24T00:00:00").getTime() + new Date().getTimezoneOffset()*60000)
This works, but it seems like there must be a better way that doesn't require created three date objects.
Do not parse strings using the Date constructor. It calls Date.parse which, despite being standardised for one version of ISO 8601 strings in ES5, is still almost entirely implementation dependent.
I'm trying to convert a date string into a date object without changing the timezone.
> new Date ("2014-10-24T00:00:00")
That string will be treated differently in different browsers. If you want it to be treated as UTC, then it is simple to parse yourself:
function parseISOAsUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0],--b[1],b[2],b[3],b[4],b[5],(b[6]||0)));
}
console.log(parseISOAsUTC('2014-10-24T00:00:00').toISOString()); // 2014-10-24T00:00:00.000Z
Now you can be certain that the string will be treated as UTC in all browsers in use (including the 20% or so still using IE 8 and lower).
If, on the other hand, you want the string to be treated as a local time, then just remove the Date.UTC part:
function parseISOAsLocal(s) {
var b = s.split(/\D/);
return new Date(b[0],--b[1],b[2],b[3],b[4],b[5],(b[6]||0));
}
console.log(parseISOAsLocal('2014-10-24T00:00:00')); // Fri 24 Oct 2014 00:00:00 <local timezone>
Here is an implementation of zerkms's solution.
new Date("2014-10-24T00:00:00".replace('T', ' '))
result
Fri Oct 24 2014 00:00:00 GMT-0500 (Central Daylight Time)