const date = new Date();
date.setDate(date.getDate() - 30);
console.log(date); // 2018-03-03T23:10:24.063Z
console.log(date + 'hello'); // Sat Mar 03 2018 15:10:59 GMT-0800 (PST)hello
What's going on here? How can I use the date value without formatting it to be human readable? Thanks!
2018-03-03T23:10:24.063Z
This is date.toISOString(), so date.toISOString() + 'hello'.
toJSON() is your friend (more often than not):
const date = new Date();
date.setDate(date.getDate() - 30);
console.log(date);
console.log(date.toString());
console.log(`${date.toJSON()}hello`);
Internally, Date.prototype.toJSON() uses Date.prototype.toISOString().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON
When concatenating a date object with a string, internally Date.prototype.toString() is being called - and that creates the output you do not want in your case.
The Date object overrides the toString() method of the Object object; it does not inherit Object.prototype.toString(). For Date objects, the toString() method returns a string representation of the object.
The toString() method always returns a string representation of the date in American English.
JavaScript calls the toString() method automatically when a date is to be represented as a text value or when a date is referred to in a string concatenation.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString
Related
I am uploading a date time to a field on a dynamics form, and the form needs to receive a UTC date time. If I do something like this:
new Date(new Date().toISOString())
If i console.log the date it shows as: Fri Dec 18 2020 14:27:39 GMT-0500 (Eastern Standard Time)
I want the object to print as the UTC time with UTC specified as the time zone, otherwise the form (expecting a date object) keeps uploading as the EST time.
Use Date.UTC
const utcDate1 = new Date(Date.UTC(96, 1, 2, 3, 4, 5));
Docs
Edit: As another user mentioned, you must use Date.UTC.
var date = new Date(Date())
var utcDate = date.toUTCString();
console.log(utcDate)
Date objects are just an offset in milliseconds from the ECMAScript epoch, 1970-01-01T00:00:00Z. They do not have a timezone. When you stringify the object you get a timestamp that depends on the method used.
Most methods (e.g. toString) use the host settings for timezone and offset and produce timestamps based on those settings.
If you want an ISO 8601 compliant string with zero offset, the use toISOString or toUTCString depending on the format you want:
let d = new Date();
console.log(`local time : ${d.toString()}`);
console.log(`toISOString: ${d.toISOString()}`);
console.log(`toUTCString: ${d.toUTCString()}`);
See How to format a JavaScript date.
In your code, the expression:
new Date(new Date().toISOString())
firstly creates a Date object for the current moment in time, then generates a timestamp per the toISOString method. That is then parsed back into a Date object, so the result is identical to:
new Date();
I'm working on a project right now where I want to get an array of dates between two end points. I've got that code working perfectly when I hard code the start and end date in.
My problem is when I used an input, the code doesn't work. How can I convert a normal date input into a UTC string?
Here's an example of what I'm on about: https://jsfiddle.net/mksvh95y/5/
<input type="date" id="bubbles" placeholder = "enter date">
<button onclick="getDate()"> Click me to get date</button>
<script>
function getDate(){
var water = document.getElementById("bubbles").value;
alert(water);
//alert(water.toUTCString());
var fire = new Date (2018,10,15);
alert(fire);
}
I want the get the 'water' variable to be formatted like the 'fire' variable.
I saw there's .toUTCstring(), but that doesn't work
This is possibly a duplicate of Why does Date.parse give incorrect results, but here's an answer that may be more suitable.
The value of a date input is an ISO 8601 format date string in the format "YYYY-MM-DD", which is what you should see from:
alert(water); // something like 2018-06-21
The format of the string returned by Date.prototype.toString is implementation dependent (though ECMAScript 2019 will standardise it). That's the format you're getting from:
alert(fire) // e.g. Thu Jun 21 2018 00:00:00 GMT+1000 (AEST)
One fix is to convert the string from the date input to a Date, then use the default toString for both outputs. But your problem then is that parsing of the ISO 8601 date string is UTC, so the dates will be different by the host timezone offset, e.g.
console.log(new Date('2018-06-21').toString()); // 21 Jun 2018
console.log(new Date(2018, 5, 21).toString()); // 21 Jun 2018
So you need to parse the string from the input as local using a simple function like:
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2]);
}
console.log(parseISOLocal('2018-06-21').toString());
console.log(new Date(2018, 5, 21).toString());
If you want to use a library like moment.js, it will parse ISO 8601 formatted date strings as local (which is consistent with ISO 8601), then convert it to a plain Date and use the default toString, e.g.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<input type="date"
onchange="console.log(moment(this.value).toDate().toString())">
I strongly recommend using the excellent MomentJS library for date mainpulation, as native support is poor:
function getDate(){
var water = document.getElementById("bubbles").value;
var waterMoment = moment(water);
alert(water.utc().format()); //outputs a UTC date string
var fire = new Date (2018,10,15);
alert(fire);
}
See the moment.utc() function and the moment.format() function for more details.
I'm using the following code to get current date and time in nodejs.
var date = (new Date()).toJSON();
after converting to JSON, it returns a wrong time with a wrong timezone as below:
2018-01-03T11:16:38.773Z
but without toJSON() it returns the real time in correct timezone
Wed Jan 03 2018 14:47:12 GMT+0330 (Iran Standard Time)
The format is different because:
The toJSON method is a built-in member of the Date JavaScript object.
It returns an ISO-formatted date string for the UTC time zone (denoted
by the suffix Z).
What you can do:
You can override the toJSON method for the Date type, or define a
toJSON method for other object types to achieve transformation of data
for the specific object type before JSON serialization.
source
If you want the same result you could just use toString instead of toJSON:
var date = new Date().toString();
2018-01-03T11:17:12.000Z === Wed Jan 03 2018 14:47:12 GMT+0330 (Iran Standard Time)
The one on the left hand side is ISO timezone and one on the right is basically the browser timezone.
(new Date()).toJSON() converts into ISO timezone
So a simple way to convert to string is
var date = (new Date()).toString();
I am wondering why those two Date objects have different output in console. In my opinion it should be the same but I can be wrong :)
var twoLinesSetup = new Date();
twoLinesSetup.setHours(0, 0, 0);
var inlineSetup = new Date().setHours(0, 0, 0)
console.log('twoLinesSetup', twoLinesSetup);
console.log('inlineSetup', inlineSetup);
And the console
twoLinesSetup: Mon May 08 2017 00:00:00 GMT+0200
inlineSetup :1494194400521
Why is it so?
twoLinesSetup contains the return value from instantiating the Date constructor, which returns a new Date instance object.
inlineSetup contains the return value from the setHours method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC
inlineSetup stores the return value of setHours. It is "A Number, representing the number of milliseconds between the date object and midnight January 1 1970"
twoLinesSetup is an actual object, which you do manipulate. The console output - the "toString" method if you want it like that, is the formatted string representation you see.
In theory you should see the same number by doing twoLinesSetup.getTime().
You're assigning the return value of the setHours() call to inlineSetup. This is not the Date object but a number representing the milliseconds of the date.
I need to convert session.lastAccessedTime object from jsp into Javascript Date object. Currently, it displays as long object. How can I convert to Javascript date object?
console.log('MaxInactive Interval == ' + ${pageContext.session.lastAccessedTime});
You can use Date.parse() method to convert date string to date object.
MDN Date.parse()
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC
Date.parse(lastAccessedTime)