Im running into an issue and due to my unfamiliarity with dates im not sure what exactly is happening.
Right now I am importing a .json file like so:
import widget from "@fixtures/widget.json";
In the .json
file I have a normal JSON object and a property I need to update thats similar to this:
"WidgetTime": "2023-01-01T12:12:10Z",
I need to update this for testing to the current date so I use a function like this:
export function addHoursToDate(hoursFromNow = 5) {
return new Date(
new Date().setTime(new Date().getTime() + hoursFromNow * 60 * 60 * 1000),
);
}
This actually works fine by default, however when I assign it to the property I get an error with typescript:
widget.WidgetTime = addHoursToDate(timeFromNow)
I get an error saying:
Type ‘Date’ is not assignable to type ‘string’.
From my understanding New Date
returns a Date
type and calling just Date
returns it as a string. However appending toString()
onto the function causing it to fail (Because I guess what I need is a ISOString?)
Im not really sure what’s going on, as it works despite the error because my guess is JavaScript is coercing it to a ISOString? But im unsure how to properly fix the error.
Thanks
There is a weird comma there. Try
return new Date(new Date().setTime(new Date().getTime() + hoursFromNow * 60 * 60 * 1000)).toISOString()
How do I output an ISO 8601 formatted string in JavaScript?