Reputation: 83
How do I convert a Javascript date to EDM Date format for OData usage?
let currentDate = new Date();
// is there a native function to convert?
The following answers seem to use outdated answers, wondering if
Latest Javascript in ECMA 2020 have a native function to convert?
https://stackoverflow.com/a/14405868/14727392
https://stackoverflow.com/a/17284978/14727392
Resources: https://www.odata.org/documentation/odata-version-2-0/json-format/
Note: conducting work in Angular 10 framework
By the way, This function does not work in Angular giving error below,
https://stackoverflow.com/a/14405868/14727392
function convertJSONDate(jsonDate, returnFormat) {
var myDate = new Date(jsonDate.match(/\d+/)[0] * 1);
myDate.add(4).hours(); //using {date.format.js} to add time to compensate for timezone offset
return myDate.format(returnFormat); //using {date.format.js} plugin to format :: EDM FORMAT='yyyy-MM-ddTHH:mm:ss'
}
Error: Property 'add' does not exist on type 'Date'; Property 'format' does not exist on type 'Date'
Upvotes: 0
Views: 4911
Reputation: 646
Your question is unclear, but this is what I assume you are trying to achieve:
const dateJSONToEDM = jsonDate => {
const content = /\d+/.exec(String(jsonDate));
const timestamp = content ? Number(content[0]) : 0;
const date = new Date(timestamp);
const string = date.toISOString();
return string;
};
console.log(
dateJSONToEDM(`/Date(1609195194804)/`)
); // Outputs "2020-12-28T22:39:54.804Z"
Upvotes: 1