moment.js 日期格式在 iOS 中不起作用

moment.js date format not working in iOS

我有一个使用 JQuery Mobile 和 PhoneGap 构建的应用程序,此代码在 iOS 中不可用,但在 android 中运行良好。我也在使用 moment.js

format for date = Thu Sep 17 2015 00:00:00 GMT-0400 (EDT)

var selecdate = new Date(date).getTime(); //Get the Unix time based on date selected from calender
var sDate = moment(selecdate); //pass the date to the moment.js library
var aDate = moment();//Get current date
var PTime = sDate.diff(aDate, 'days');//Calculate the different between current date and selected date using moment.js library.


if (PTime < 0){ //If the selected date is before today return false.
alert("Select a Future Date");
return false;
}

有人可以帮忙吗?不确定为什么这个简单的代码在 iOS 中不起作用。在 Android 中,如果用户选择今天日期之前的任何日期,PTime 将小于 O 并且它会在 iOS 中提醒用户 'Select a Future Date' 它完全忽略 if 语句。

new Date(dateObject) 的行为未由 ECMAScript 规范定义。大多数情况下,它会等价于new Date(dateObject.valueOf()),相当于原来的dateObject。我不是 100% 肯定,但有可能某些环境(例如较旧的 Android 设备)可能没有实现它。如果未实现,您的代码可能会在第一行停止。

而且,完全没有必要。你可以这样做:

if (moment(date).isBefore(moment().startOf('day'))) {
    alert("Select a Future Date");
    return false;
}

或者您甚至可以毫不费力地执行此操作,如下所示:

function getStartOfToday() {
    var dt = new Date();

    dt.setHours(0);
    dt.setMinutes(0);
    dt.setSeconds(0);
    dt.setMilliseconds(0);  

    // Handle browser-specific DST edge case when day starts at 1:00 AM
    // Ex: Firefox on Oct 18, 2015 in Brazil
    if (dt.getHours() !== 0) {
        dt.SetTime(dt.getTime() + 36e5);
    }

    return dt;
}

var today = getStartOfToday();
if (date < today) {
    alert("Select a Future Date");
    return false;
}