dayjs (relativeTime)上有插件,它将返回人类可读的字符串,而不是数字。有什么办法只返回号码吗?
就像这样
dayjs('2020-07-1').from(dayjs('2020-07-9')) // -8
dayjs('2020-07-1').from(dayjs('2020-07-1')) // 0
dayjs('2020-07-11').from(dayjs('2020-07-9')) // 2 发布于 2020-07-09 05:06:07
工作代码!!
以diff()作为第二个参数从dayjs库中使用'day'方法
console.log(dayjs('2020-07-1').diff('2020-07-9', 'day')); // -8
console.log(dayjs('2020-07-1').diff('2020-07-1', 'day')); // 0
console.log(dayjs('2020-07-11').diff('2020-07-9', 'day')); // 2<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.29/dayjs.min.js" integrity="sha512-APVsMirhHF2o3YdCSwYonM7egfT589pTqyoy5hIzEbs9sAGJSbEI6ssXUwngHjaq4V/GmmmpgqrcLSvsO+gsJQ==" crossorigin="anonymous"></script>
注意:'day' 可以替换为 'd__‘,它是一个简写的
发布于 2020-07-09 04:58:21
如果没有dayjs,我可以提出一些简单的方法来获得您想要的结果,如下所示。
function getDayDifference(from, to) {
let diffInMilliseconds = new Date(from) - new Date(to);
// divide with (1000*60*60*24) to get difference in days.
let days = Math.round(diffInMilliseconds / (1000 * 60 * 60 * 24));
console.log(days);
return days;
}
getDayDifference('2020-07-1', '2020-07-9'); // -8
getDayDifference('2020-07-1', '2020-07-1'); // 0
getDayDifference('2020-07-11', '2020-07-9'); // 2
或者,您也可以用dayjs为dayjs.prototype.getDayDifference = function(to) {...}定义自己的扩展方法。你可以在下面检查一下。
dayjs.prototype.getDayDifference = function(to) {
//86400000 = (1000 * 60 * 60 * 24)
return Math.round((this.$d - to.$d) / 86400000);
}
console.log(dayjs('2020-07-1').getDayDifference(dayjs('2020-07-9'))); // -8
console.log(dayjs('2020-07-1').getDayDifference(dayjs('2020-07-1'))); // 0
console.log(dayjs('2020-07-11').getDayDifference(dayjs('2020-07-9'))); // 2<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.29/dayjs.min.js" integrity="sha512-APVsMirhHF2o3YdCSwYonM7egfT589pTqyoy5hIzEbs9sAGJSbEI6ssXUwngHjaq4V/GmmmpgqrcLSvsO+gsJQ==" crossorigin="anonymous"></script>
https://stackoverflow.com/questions/62807420
复制相似问题