5

I am writing a date adapter for Angular Material, and need a function that returns a boolean if the provided object is a luxon DateTime.

Something like this (from moment):

isDateInstance(obj: any): boolean {
    return moment.isMoment(obj);
  }

What I have is this so far - is this good enough?:

isDateInstance(obj: any): boolean {
      try {
          const luxonObject = DateTime.fromObject(obj);
          return luxonObject.isValid;
      } catch (error) {
          return false;
      }
  }
4

1 回答 1

3

我认为您的代码很好,我建议您可以使用 native instanceof

const DateTime = luxon.DateTime;

function isDateInstance(obj) {
    return obj instanceof DateTime;
}

console.log( isDateInstance('') );
console.log( isDateInstance({}) );
console.log( isDateInstance(new Date()) );
console.log( isDateInstance(DateTime.local()) );
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

编辑:

Luxon 在其中添加了isDateTime方法v.1.6.0

检查对象是否为 DateTime。跨上下文边界工作

因此更新的解决方案可能如下:

const DateTime = luxon.DateTime;

function isDateInstance(obj) {
    return DateTime.isDateTime(obj);
}

console.log( isDateInstance('') );
console.log( isDateInstance({}) );
console.log( isDateInstance(new Date()) );
console.log( isDateInstance(DateTime.local()) );
<script src="https://cdn.jsdelivr.net/npm/luxon@1.10.0/build/global/luxon.js"></script>

v.1.6.0直到v.1.8.3 isDateTime将给予undefined而不是false由于问题

于 2018-05-17T09:45:08.747 回答