JavaScript中BigInt类型时间戳转DateTime及自定义格式化实现方法
解答
BigInt 时间戳转 Date 实现
JavaScript 内置 Date 构造函数确实仅支持接收 number 类型的毫秒时间戳参数,但常规业务场景下毫秒时间戳远小于 Number.MAX_SAFE_INTEGER(值为 9007199254740991,对应公元275760年),直接把 BigInt 转为 number 不会丢失精度,转换代码如下:
// 你的BigInt类型时间戳 const bigIntTime = 1630017759934n; const date = new Date(Number(bigIntTime));
自定义日期格式化实现
快速实现 yyyyMMdd 格式输出
如果只需要固定输出 yyyyMMdd 格式,直接用以下极简实现即可:
function formatYyyyMmDd(date) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}${month}${day}`; } // 调用示例,针对你给出的时间戳输出为 20210827 const formattedStr = formatYyyyMmDd(new Date(Number(1630017759934n)));
类 Java DateTimeFormatter 通用格式化实现
如果需要类似 Java 中 DateTimeFormat.forPattern 的按自定义模式输出能力,可以实现通用格式化方法,支持扩展任意占位符:
function formatDateByPattern(date, pattern) { const replacements = { 'yyyy': date.getFullYear(), 'MM': String(date.getMonth() + 1).padStart(2, '0'), 'dd': String(date.getDate()).padStart(2, '0'), 'HH': String(date.getHours()).padStart(2, '0'), 'mm': String(date.getMinutes()).padStart(2, '0'), 'ss': String(date.getSeconds()).padStart(2, '0') }; return pattern.replace(/yyyy|MM|dd|HH|mm|ss/g, match => replacements[match]); } // 调用示例,按yyyyMMdd格式输出 const result = formatDateByPattern(new Date(Number(1630017759934n)), 'yyyyMMdd');
需要新增其他格式占位符时,只需在 replacements 对象中新增对应规则即可。
内容的提问来源于stack exchange,提问作者Teddy Dong
相关产品推荐
相关产品推荐

