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