如何检查obj是否为luxon类型?

时间:2018-05-15 11:40:03

标签: luxon

我正在为Angular Material编写日期适配器,如果提供的对象是luxon DateTime,则需要一个返回布尔值的函数。

像这样(从片刻开始):

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

到目前为止我所拥有的是 - 这还不错吗?:

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

1 个答案:

答案 0 :(得分:2)

我认为您的代码很好,我建议您使用原生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>
&#13;
&#13;
&#13;

修改

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

  

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

所以更新后的解决方案如下:

&#13;
&#13;
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()) );
&#13;
<script src="https://cdn.jsdelivr.net/npm/luxon@1.10.0/build/global/luxon.js"></script>
&#13;
&#13;
&#13;

v.1.6.0v.1.8.3 isDateTimeundefined代替false {{1}}。{/ p>