返回两个日期之间的天数不起作用

问题描述 投票:1回答:4

我有一个小代码,从json文件中获取日期。并返回它到期前剩余的天数。

如何在控制台日志中返回NaN。

var start = "2019/03/12";
var end = "2020/03/12";
days = (end- start) / (1000 * 60 * 60 * 24);
console.log(Math.round(days));

这应该是正确的。但它不起作用。

javascript jquery date time
4个回答
1
投票

你需要将endstart改为Date

var start = "2019/03/12";
var end = "2020/03/12";
days = ( new Date(end)- new Date(start) ) / (1000 * 60 * 60 * 24);
console.log(Math.round(days));

0
投票

你必须将你的字符串日期转换为javascript日期,但总体而言我建议使用时刻,因为javascript日期可能会很痛苦

要将您的字符串转换为javascript日期类型,您可以这样做

var mydate = new Date('2011-04-11T10:20:30Z'); // <--- you have to format it

方法2)

new Date('2011', '04' - 1, '11', '11', '51', '00')

如果你想使用片刻,你可以这样做:

var mydate = moment("2014-02-27T10:00:00").format('DD-MM-YYYY'); // <-- here inside the format function you can define how your string get's parsed

如果有帮助,请标记为正确答案,谢谢!


0
投票

试试这个...使用Date对象

var start = new Date("2019/03/12");
var end = new Date("2020/03/12");
days = (end - start) / (1000 * 60 * 60 * 24);
console.log(Math.round(days));

-1
投票

使用diffmoment.js函数。但是你必须在使用前格式化它。

const format = date => date.replace(/\//g, '-') 

var start = moment(format("2019/03/12"));
var end = moment(format("2020/03/12"));

console.log(end.diff(start, 'days'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.