【问题标题】:Comparing Dates of Different Formats比较不同格式的日期
【发布时间】:2016-10-07 20:48:42
【问题描述】:

我正在尝试在 AngularJS 中编写一段类似于下面的代码:

$scope.isAfterToday= function(inputDate){
    if(inputDate > Date.now().toString()){
        return true;
    } else {
        return false;
    }
}

但是,问题在于参数 inputDate 的格式为“2016-10-12T00:00:00”,这与 Date.now() 函数的格式不同。除了从每种格式中解析出月、日和年并比较两者之外,还有没有一种简单的方法可以在这两种格式之间进行转换?

感谢您的帮助!

【问题讨论】:

标签: javascript angularjs date


【解决方案1】:
$scope.isAfterToday=function(inputDate){
    //First get the first time *after* today:
    var t = new Date().setHours(0,0,0,0);//0 seconds into this morning
    t.setDate(t.getDate()+1); //midnight tomorrow
    new Date(inputDate) > t );
};

不需要外部库。可以直接比较Date对象,Date构造函数接受多种日期格式字符串作为输入。

对于Date对象比较,可以使用常用的数值比较器:

<
>
<=
>=

不要使用==,它会比较它们的对象引用而不是它们的值。

【讨论】:

  • 今晚午夜”通常是在一天结束时发生的。将小时数设置为 0 是一天开始时的午夜,所以真的是“今天早上的午夜”。
【解决方案2】:

您可以将 inputDate 包装在标准 Date 对象中,如下所示:

new Date("2016-10-12T00:00:00").getTime(); // you'll get 1476230521000

new Date().toISOString(); 反转

【讨论】:

  • "你会得到 1476230521000" 仅适用于同一时区的用户,如果字符串是用当前规则解析的。
【解决方案3】:

您可以使用 Date 对象将您的 inputDate 转换为您可以比较的毫秒数。

var convertedInput = new Date(inputDate);

如果您需要换一种方式输出看起来不错的东西,技术上没有格式化输出。但是将毫秒解析为日期并不是那么难!

var today = new Date();
var day = today.getDate();
var month = today.getMonth() + 1; //Month is 0-based for some reason
var year = today.getFullYear();
var datenow = year + "-" + month + "-" + day;

【讨论】:

    猜你喜欢
    • 2022-11-17
    • 1970-01-01
    • 2020-10-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    相关资源
    最近更新 更多