Javascript date calculation

2019-06-27 17:02发布

I have date field,Onclick on date feild,i have to calculate the date with the current date .if entered date is one month older than today date.I have to popup amessage saying date is olderthan 1 month.

Date format is "yyyy-MM-dd".i want to compare with date "1984-03-20" to today date "2011-04-14".it should return number of months.

Any hints on this. Regards,

Chaitu

标签: javascript
7条回答
\"骚年 ilove
2楼-- · 2019-06-27 17:26

Maybe this could help to you:

http://www.ozzu.com/programming-forum/javascript-date-comparison-t46552.html

<script language="JavaScript">

var days = 0;
var difference = 0;

Christmas = new Date("December 25, 2005");

today = new Date();

difference = Christmas - today;

days = Math.round(difference/(1000*60*60*24));

</script>
查看更多
3楼-- · 2019-06-27 17:32

See this discussion it has demos for getting date difference in javascript. Also this is a good example: javascript-date-difference-calculation it shows how to get difference in month, in week or in year.

查看更多
Animai°情兽
4楼-- · 2019-06-27 17:32
var dt = new Date('02 Jul 2009');
dt.setMonth(dt.getMonth() – 1);

You can read up about js Date object to see what formats it can accept.

A blog about JS Date formats

查看更多
时光不老,我们不散
5楼-- · 2019-06-27 17:33

The easiest way to compare dates in javascript is to first convert it to a Date object and then compare these date-objects.

Below you find an object with below function:

dates.inRange (d,start,end)

Returns a boolean or NaN:

    * true if d is between the start and end (inclusive)
    * false if d is before start or after end.
    * NaN if one or more of the dates are illegal.
查看更多
Animai°情兽
6楼-- · 2019-06-27 17:37

You can do something like that:

   <script type="text/javascript">

        function checkdate (){

           var today = new Date()

           var dating = document.getElementById("date").attr("value");

           var new = new Date(dating);

           var diff = today - new;

           var days = Math.round(diff/(1000*60*60*24));

           if (days >= 30){

                alert("more than one month!");
           }
      }

    </script>

    <html><body>
       <input type="text" id="date" onClick="checkdate();"/>
    </html></body>
查看更多
三岁会撩人
7楼-- · 2019-06-27 17:42

This would work. Pass the value of the field to dateString onclick and the code will determine whether the date is older than 1 month or not.

var dateString = '3/26/2011';
var selectDate = new Date(dateString); // convert string to date
var monthOld = new Date();

monthOld.setDate(monthOld.getDate() - 30); // subtract 30 days

if (selectDate < monthOld) {
    alert('older than one month');
}
else alert('ok');

Demo: http://jsfiddle.net/cw4vb/

查看更多
登录 后发表回答