Reputation: 456
I have a date object in javascript and I'm trying to get it to return a string in that format.
private convertEpochToDate(epoch: string) {
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
if (!epoch) return "nodate";
var date = new Date(0);
let milliseconds = parseInt(epoch);
date.setUTCMilliseconds(milliseconds);
return date;
}
Instead of the date object, I need the date to be formatted in the string just like this: 2020-05-15T05:00:00Z
Upvotes: 1
Views: 208
Reputation: 980
convertEpochToDate(epochTime: number), says it's mandatory. so you do not require
if (!epoch) return "nodate";
convertEpochToDate(epochTime?: number), now it's optional
if (!epoch) return "nodate";
or,
const epochString = !!date ? this.convertEpochToDate(date) : "no date";
(epochTime: number) since you are expecting date in milliseconds-which'd be a number- eg: new Date().getTime();
private convertEpochToDate(epochTime: number): string => new Date(epochTime).toISOString();
(epochTime: Date) if you are passing as a date object. mind it's "Date", not "date".
private convertEpochToDate(epochTime: Date): string => epochTime.toISOString();
Upvotes: 0
Reputation: 52
You should check out the moment.js library which has every kind of date functionality you would ever want.
Upvotes: -1
Reputation: 386604
Just take Date#toISOString
.
console.log(new Date().toISOString());
Upvotes: 2