我试图在moment.js中获取今天日期和目的地日期之间的日期差异,这就是我所做的:
var now = moment().format('DD/MM/YYYY HH:mm:ss');
var then = moment("15/09/2017 14:20:30").format('DD/MM/YYYY HH:mm:ss');
//here i try the difference
var diffTime = moment.utc(moment(now).diff(moment(then)));
console.log("differenza per countdown "+diffTime);
console.log返回我"无效的日期"但是,如果我现在使用"那么"它返回0(这是正确的),如何创建正确的格式化数据?
答案 0 :(得分:4)
为什么要将字符串格式化为字符串以便再次解析它?这样做没有意义。
对差异使用moment.duration:
var now = moment();
var then = moment("15/09/2017 14:20:30", "DD/MM/YYYY HH:mm:ss");
//here i try the difference
var diffTime = moment.duration(then.diff(now));
console.log("differenza per countdown "+diffTime);
console.log("humanized: " + diffTime.humanize(true));
console.log(diffTime.days() + "/" + diffTime.months() + "/" + diffTime.years() + " " + diffTime.hours() + ":" + diffTime.minutes() + ":" + diffTime.seconds());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
答案 1 :(得分:1)
您的日期格式不是标准格式,在这种情况下,将其明确指定为第二个参数,否则解析将在不同浏览器中失败。
moment("15/09/2017 14:20:30", 'DD/MM/YYYY HH:mm:ss')
回答是的,转换为字符串并将其解析回日期没有任何价值,除非你之间有其他逻辑。
window.onload = function(){
var now = moment().format('DD/MM/YYYY HH:mm:ss');
var then = moment("15/09/2017 14:20:30", 'DD/MM/YYYY HH:mm:ss').format('DD/MM/YYYY HH:mm:ss');
//here i try the difference
var diffTime = moment.utc(moment(now, 'DD/MM/YYYY HH:mm:ss').diff(moment(then, 'DD/MM/YYYY HH:mm:ss')));
console.log("differenza per countdown "+diffTime);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
对我来说,结果是NaN
,但日期解析可能因浏览器而异。
window.onload = function(){
var now = moment().format('DD/MM/YYYY HH:mm:ss');
var then = moment("15/09/2017 14:20:30").format('DD/MM/YYYY HH:mm:ss');
//here i try the difference
var diffTime = moment.utc(moment(now).diff(moment(then)));
console.log("differenza per countdown "+diffTime);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
答案 2 :(得分:0)
您也可以使用Date.parse()
将日期转换为毫秒,然后找出差异。