Javascript计算/匹配日期和日期时间。现在

时间:2014-02-01 09:18:21

标签: javascript date datetime

我在下面的文本框中有日期值

01.01.2014

我想将文本框日期值与Datetime.now匹配

Datetime.Now is 01.02.2014

我想计算datetime.now和textbox日期值。

输出必须低于

Datetime.now's days - DateTextbox value = 30 days

Datetime.now's month - DateTextbox value = 1 month

Datetime.now's year - DateTextbox value = 0 year 

那么我怎么能只使用javascript来做到这一点?

HTML

<input type="text" id="DateTextBox"/>

使用Javascript:

<script>
    function GetDateButtonClick() {
        $.ajax({
            type: "POST",
            url: "Home/MyUrl",
            cache:false,
            data:
                {
                    MyDate: $("#DateTextBox").val(),
                },
            success: function (mydata) {

            }
        });
    }
</script>

任何帮助都会被证实。

感谢。

2 个答案:

答案 0 :(得分:0)

获取当前日期

var today = new Date();

从文本框中检索日期并转换为日期对象,如下所示

var myDate = new Date("2014/1/1");

用于comaparison

var timeDiff = Math.abs(myDate.getTime() - today.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); //this will give number of days

对于一年中的这个月,我会把它留给你...希望这有帮助

<强>更新

var diffMonths = Math.round(((diffDays / 30); // for months
var diffYrs = Math.round(diffMonths / 12); // for years

答案 1 :(得分:0)

这将找到两个日期之间的年,月,日,小时,分钟数。

var today = new Date();
var inputDate = new Date($("#DateTextBox").val());// from your input

var diffSecs = (inputDate - today)/1000; // seconds between today & inputDate

var diffMins = Math.round(diffSecs / 60); // minutes
var diffHrs = Math.round(diffMins / 60); // hours
var diffDays = Math.round(diffDays / 24); // days
var diffMonths = Math.round(((diffDays / 30); // months
var diffYrs = Math.round(diffMonths / 12); // years

alert(diffYrs + " years, " + diffMonths + " months, " + diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes.");