Search code examples
angularjsmomentjsepoch

Epoch 0 to Date conversion using momnet.js


I need to convert my epoch date to a Date object. I did this using the following code.

let abc = moment(maintenance.actualEndDate * 1000).format('DD/MMM/YYYY hh:mm');

but there is a high chance to 0 as the value for 'maintenance.actualEndDate'. in this case the transalated date is showing the value as '01/01/1970 12:00'.

I actually need as an empty string in variable abc if the maintenance.actualEndDate is 0

I'm working on angular 4, is there any optimal solution to this?


Solution

  • If what you need is converting non-zero timestamps to a formatted date, and zero timestamps as empty string, a dedicated function would be nice:

    function formatTimestamp(secondsSinceEpoch) {
        return secondsSinceEpoch===0 ? '' : moment.unix(secondsSinceEpoch).format('DD/MMM/YYYY HH:mm');
    }
    //...
    let abc = formatTimestamp(maintenance.actualEndDate);
    

    (But this has nothing specific to angular)