用Javascript将毫秒准确地转换为年(带小数)



我正在尝试构建一个类似的应用程序。它的作用是以年为单位提供自特定日期以来的时间,小数点后约有10-15位。我已经看了这篇文章,但每个答案要么没有考虑闰年,要么没有这个应用程序所要求的小数精度。我对Javascript中的日期不太熟悉,有人能帮我吗?

您可以使用Day.js.

如果使用npm i dayjsyarn add dayjs在本地安装库,则应使用以下示例

import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
dayjs.extend(duration);
const getDuration = (start: Date | dayjs.Dayjs) => {
// Gets the difference between now and some other date in ms
const diff = dayjs().diff(start);
// Converts the duration in ms to years
return dayjs.duration(diff).asYears();
};
const dt = new Date('1990-10-09 09:30:15');
const dj = dayjs('2000-01-01').startOf('day');
console.log(getDuration(dt));
console.log(getDuration(dj));

您也可以像下面的代码片段一样直接从cdn加载它。

dayjs.extend(window.dayjs_plugin_duration)
const getDuration = (start) => {
const diff = dayjs().diff(start);
return dayjs.duration(diff).asYears();
};
const dt = new Date('1990-10-09 09:30:15');
const oneYearAgo = dayjs().subtract(1, 'year');
const oneYearAndOneDayAgo = oneYearAgo.subtract(1, 'day');
console.log(getDuration(dt));
console.log(getDuration(oneYearAgo));
console.log(getDuration(oneYearAndOneDayAgo));
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/duration.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>

相关内容

  • 没有找到相关文章

最新更新