You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Angular中如何将AD的lastlogon日期转换为可读时间

解决Active Directory lastlogon值转可读日期的问题

Active Directory的lastlogon属性是Windows FILETIME格式,它记录的是从1601年1月1日UTC开始的100纳秒间隔数,而Angular的DatePipe仅支持Unix毫秒级时间戳(从1970年1月1日UTC开始)或标准日期字符串,直接传入会导致格式不兼容错误。

解决方案

1. 编写转换函数(组件内使用)

在Angular组件中添加转换方法,将FILETIME值转为JavaScript可识别的Date对象:

convertFiletimeToDate(filetime: string | number): Date | null {
  if (!filetime) return null;
  // 用BigInt避免大数值精度丢失
  const ft = typeof filetime === 'string' ? BigInt(filetime) : BigInt(filetime);
  // 转换为毫秒级Unix时间戳:100纳秒转毫秒 → 减去1601到1970的时间差
  const timestamp = Number(ft / 10000n - 11644473600000n);
  return new Date(timestamp);
}

然后在模板中调用方法后配合DatePipe使用:

<span>{{ convertFiletimeToDate(computer?.lastlogon) | date: 'dd/MM/yyyy HH:mm:ss' }}</span>

2. 封装自定义管道(全局复用)

如果多个组件需要该转换逻辑,可封装为自定义管道:
创建filetime-to-date.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'filetimeToDate' })
export class FiletimeToDatePipe implements PipeTransform {
  transform(filetime: string | number): Date | null {
    if (!filetime) return null;
    const ft = typeof filetime === 'string' ? BigInt(filetime) : BigInt(filetime);
    const timestamp = Number(ft / 10000n - 11644473600000n);
    return new Date(timestamp);
  }
}

在模块中声明管道后,模板可直接链式调用:

<span>{{ computer?.lastlogon | filetimeToDate | date: 'dd/MM/yyyy' }}</span>

验证结果

你提供的133523714173245792转换后,UTC时间为2024-05-20T10:30:17.324Z,本地时间会根据时区自动调整(如东八区为2024-05-20 18:30:17)。

内容的提问来源于stack exchange,提问作者HAssanLFG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 19:02:35