2

I am comparing two date variables.

For whatever reason, from C# API to Javascript, they sometimes convert as 1) string or 2) Date or even 3) Moment due to previous company code.

Typescript states they are Date in interface below, but in Javascript runtime, it changes.

So now, in comparing two dates, is there an easy way to simplify code below? Converting everything to Date, and conducting getTime() comparison.

export interface Product {
    productName?: string;
    recordDate?: Date;
}

if (product1.recordDate instanceof Date) {
    dateVar1 = product1.recordDate;
} else if (typeof product1.recordDate === 'string') || product1.recordDate instanceof String)) {
    dateVar1 = new Date(product1.recordDate);
} else if (product1.recordDate instanceof moment) {
    dateVar1 = ((product1.recordDate as any) as moment.Moment).toDate();
}

if (product2.recordDate instanceof Date) {
    date2Var = product2.recordDate;
} else if (typeof product2.recordDate === 'string') || product2.recordDate instanceof String)) {
    date2Var = new Date(product2.recordDate);
} else if (product2.recordDate instanceof moment) {
    date2Var = ((product2.recordDate as any) as moment.Moment).toDate();
}


if date1Var.getTime() === date2Var.getTime() {
  return true;
} else {
  return false;
}

using Angular environment ,

Resources:

Converting a string to a date in JavaScript

1 Answers1

0

You can use Moment. Just pass string or Date or Moment value:

dateVar1 = moment(product1.recordDate).toDate();

Working Example

const stringDate = "2020-08-01";  // string
const dateDate = new Date();      // Date
const momentDate = moment();      // Moment

console.log(moment(stringDate).toDate());
console.log(moment(dateDate).toDate());
console.log(moment(momentDate).toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
critrange
  • 5,652
  • 2
  • 16
  • 47