现在的日期大于给定的日期值 [英] Date now greater than date value given

查看:86
本文介绍了现在的日期大于给定的日期值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须尝试确定来自隐藏字段(格式为mm/dd/yyyy)的日期是否小于今天.如果是的话,我想让此人知道订阅已过期.我曾在某些场合下进行过这项工作,但工作做起来还不够可靠?

I am having to try to determine whether a date from a hidden field, formatted mm/dd/yyyy, is less than today. if it is, I want to let the person know that a subscription has expired. I have had this working on some occasions but it is not reliably doing it??

//this is the expiration date that is in a hidden field
var expireDate = $("#expire").val();

//here I am trying to setup a new date for today and change the output to match the date
//format for the hidden field, i.e. mm/dd/yyyy
var a = new Date();
var b = a.toISOString().split("T")[0].split("-");
var ca = b[1] + "/" + b[2] + "/" + b[0];


//now I want to compare the 2 and if the expiration date is less than today, display a warning message                      
if (expireDate < ca) {
   $("<div class=\"message-warning\">This subscription is expired</div>")
    .insertAfter("#enddate");
};

推荐答案

您正在比较字符串的数值,该数值恰好是mm/dd/yyyy格式的日期的字符串表示形式.我猜您的不一致"结果是,如果旧日期早于今天,则该日期有效.

You're comparing the numerical value of strings, which happen to be the string representation of dates in mm/dd/yyyy format. I'm guessing that your "inconsistent" results are that it works if the old date is an earlier month than today.

不是将a转换为字符串,而是将expireDate转换为Date对象.然后比较.

Instead of converting a to a string, convert expireDate to a Date object. Then compare.

var expireDateStr = $("#expire").val();
var expireDateArr = expireDateStr.split("/");
var expireDate = new Date(expireDateArr[2], expireDateArr[0], expireDateArr[1]);
var todayDate = new Date();

if (todayDate > expireDate) {
   $("<div class=\"message-warning\">This subscription is expired</div>")
    .insertAfter("#enddate");
};

这篇关于现在的日期大于给定的日期值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆