Search code examples
jsonmomentjsdate-comparison

Check the date is greater than 0001-01-01 in Moment.js


I have a function which formats date using,

export function FormatDate(date: string) {
if (date != null) {
    return moment.utc(date).format('DD MMM YYYY');
}
else
    return "";
}

But the issue is that null dates are received as "0001-01-01" (DateTime Min value). how can I check it with moment js?

Could not find a straight forward way to do it. Following code works, but it's ugly,

new moment("0001-01-01").format("DD MMM YYYY") == moment.utc(date).format("DD MMM YYYY")

The "date" I receive is in "/Date(-62135596800000)/" format.

I tried, moment.utc(date).isAfter("0001-01-01") and it's not working as well, returns true.

What is the best way to check serialized date is not the minimum date?


Solution

  • I think you are missing the timezone part when comparing the dates. Please see the below code and let me know if this is what is required:

    var minDate = moment.utc("0001-01-01"); // minimum value as per UTC
    
    var receiveDate = moment("/Date(-62135596800000)/"); // replace with variable
    if(moment.utc(receiveDate).isAfter(minDate)){
         alert('yebo !');
    }