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)
Related
If I run new Date() on my local node I get it in UTC format:
2017-08-16T10:04:45.809Z
If I run it on my test server, I get
Wed Aug 16 2017 12:04:49 GMT+0200 (CEST)
Both times are correct. In neither cases the result is string, as far as I know. Why am I getting different format for the date, depending where I run the function? What can affect the output of new Date()?
new Date() returns a date object. What you see is the date object converted to string (to print it out) applying the locale that can be different on two machines. Please, also note that new Date() returns the date and time including time zone set on the machine where the command is executed
I have a bunch of date fields (not datetime) in SQL Server. When they are fetched by the web server and sent to the client as JSON a time stamp is appended automatically. So instead of receiving just 2016-09-27 I get 2016-09-27T00:00:00.
When the user interacts with the uiBootstrap calendar control it automatically parses that string into a javascript date object and applies a 4 hour offset for the timezone. When this is sent back to the server it's sent as 2016-09-26T20:00:00. Now my date is off by a day. Also the next time it's fetched it will happen again. But this time it will start at 2016-09-26T00:00:00 and will roll back to 2016-09-25T20:00:00. Each cycle between client and server loses a day.
How do I keep my dates from changing? I'm looking at moment.js but so far haven't really figured out how it can help me.
EDIT
I've setup a test function to try different methods of converting datetimes back and forth.
console.log('JSONDate: ' + JSONDate);
var dt = new Date(JSONDate);
console.log('JS Converted Date: ');
console.log(dt);
console.log('Date converted back to string: ' + dt.toISOString());
Here's the output:
JSONDate: 2016-10-02T00:00:00
JS Converted Date: Sun Oct 02 2016 00:00:00 GMT-0400 (Eastern Daylight Time)
Date converted back to string: 2016-10-02T04:00:00.000Z
In this example the date is now 4 hours ahead.
EDIT 2
Web server is running .net, specifically WebAPI 2. I'm using Entity Framework 6 to communicate between web server and SQL Server 2012.
Ideally, your dates would be serialized in the JSON as just dates. Instead of 2016-10-02T00:00:00, you'd have 2016-10-02. The problem is that .NET doesn't have a built in Date type. It only has DateTime. There are alternatives, such as LocalDate in Noda Time, as discussed in this answer.
However, assuming you don't want to change anything on the back-end, the way to handle this is just to make sure the input date/time is treated as local time, and never converted to/from UTC. This should be the default behavior when you parse the string into a Date object when the string is like 2016-10-02T00:00:00, but the behavior has changed a few times over the years, so if you are potentially dealing with older browsers, you may get some that interpret it as UTC instead.
As far as output goes, the toISOString method of the Date object always outputs in UTC - which is the source of your conversion error. If you want an ISO8601 string in local time - you'd have to construct one yourself using the various accessor functions (getFullYear, etc.), handling zero-padding, and ensuring months are incremented to be 1-based instead of 0-based.
The easier solution is to use moment.js, which can handle this for you.
var d = moment('2016-10-02T00:00:00').toDate(); // now you have a `Date` object
var s = moment(d).format("YYYY-MM-DD[T]HH:mm:ss"); // now you have a string again
Of course, if you don't need the time portion, you can omit it from the format string and the rest should still work out ok.
You could try getting the offset and applying it back to the date. Something like this:
var d = new Date('2016-09-27'); //Mon Sep 26 2016 20:00:00 GMT-0400 (EDT)
new Date(d.getTime() + d.getTimezoneOffset() * 60 * 1000) //Tue Sep 27 2016 00:00:00 GMT-0400 (EDT)
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
I am based in Australia and while new Date() give me the current date and time in Australia, for instance
Fri Aug 26 2016 09:16:16 GMT+1000 (AUS Eastern Standard Time)
, if I write new Date().toJSON()
I get 2016-08-25T23:20:08.242Z,
how can I get the same format as in yyyy-mm-ddThh:mn:ss but keeping my local day and time, ie it should be the 26 and not the 25th.
Edit: when I write programmatically new Date(2016, 11, x) with var x = 31, using toJSON() I have no guarantee to see displayed 2016-12-31 because of timezones, so was wondering is there is a different javascript function that would give me the intended result.
I would use moment.js for that.
var date = moment("Fri Aug 26 2016 09:16:16 GMT+1000");
console.log(moment(date).format('YYYY-MM-DD T hh:mm:ss'));
https://jsfiddle.net/Refatrafi/ys4nu8o9/
toJSON() returns timestamps in ISO 8601 format. Z at the end of string means that used UTC. Date objects in ECMAScript are internally UTC. The specification for Date.prototype.toJSON says that it uses Date.prototype.toISOString, which states that "the timezone is always UTC".
The date isn't wrong, it's in UTC. Without timezone information, yyyy-mm-ddThh:mn:ss is meaningless unless you explicitly want to assume that it's in the AEST timezone.
If you're transmitting the date as a string to be parsed back into some sort of Date-like object later on (by your webserver, for example), there's nothing you need to do. 2016-08-25T23:20:08.242Z unambiguously refers to the same point in time no matter what you use to parse it.
If you're trying to format the date object and display it somewhere, you can extract the different parts of the Date object and build up the representation you want:
function format_date(d) {
var pretty_date = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join('-');
var pretty_time = [d.getHours(), d.getMinutes(), d.getSeconds()].join(':');
return pretty_date + 'T' + pretty_time;
}
As the other answers have pointed out, if you plan on working more with dates, consider using a library that makes it easier. JavaScript doesn't have a very rich API, so you'll have to write more code.
I'm working on a JavaScript application. I have two different String dates 31/10/2013 and 1/11/2013 and I create an instance of these two dates with new Date(string).getTime();
But it shows this (the same date ) as the result:
console.log(date_s + " after new date " + date );
31/10/2013 after new date Fri Nov 1 00:00:00 UTC 2013
1/11/2013 after new date Fri Nov 1 00:00:00 UTC 2013
You haven't a valid string in you new Date(string)
Some example to initialize dates
var my_date=new Date(2013,10,31)
and all the documentation on http://www.w3schools.com/js/js_obj_date.asp
31/10/2013 is not a valid date string unless you've got maybe some localization going on. To the default localization settings for en-US, it should be 10/31/2013. What your string means is "month 31 of 2013" which pushes new Date('31/10/2013') to be some time in 2015 because that's where it resolves the date due to that "month 31."
If you want an easy solution, try moment.js - a powerful javascript date parser/formatter/validator/manipulator.
In moment, you can parse date with the syntax like this [doc]:
//this will gives you a correct date object
moment('31/10/2013', 'DD/MM/YYYY').toDate();
Else, you can always welcome to split and rebuild the date object.