Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS日期对比 #11

Closed
Wscats opened this issue May 3, 2016 · 0 comments
Closed

JS日期对比 #11

Wscats opened this issue May 3, 2016 · 0 comments
Labels

Comments

@Wscats
Copy link
Owner

Wscats commented May 3, 2016

今天刚好用到这个函数,写了一个日期对比的例子

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>写一个JS对比时间的例子</title>
    </head>

    <body>
    </body>
    <script>
        function compareTime(a, b) {
            var arr = a.split("-"); //log [2016,04,06]
            var start = new Date(arr[0], (arr[1] - 1), arr[2]);
            var starts = start.getTime(); //输出时间戳进行对比
            var arrs = b.split("-");
            var end = new Date(arrs[0], (arrs[1] - 1), arrs[2]);
            var ends = end.getTime();
            if (starts >= ends)
                console.log('开始时间大于结束时间');
            else
                console.log('开始时间小于结束时间');
        }
        compareTime('2016-05-03', '2016-05-04');
    </script>

</html>

有一点要注意的就是这一句
var starttime = new Date(arr[0], (arr[1] - 1), arr[2]);
月份记得在函数里面减去1
因为在Javascript中,月份的数值是从0到11之间的整数(1月至12月),例如5就是代表6月,
这里要是要注意的
其他的话按照正常转换为时间戳进行对比即可

后面再增加一个方法就是判断时间是星期几,看改进的例子

function compareTime(a, b) {
            var arr = a.split("-"); //log [2016,04,06]
            var start = new Date(arr[0], (arr[1] - 1), arr[2]);
            var starts = start.getTime(); //输出时间戳进行对比
            var arrs = b.split("-");
            var end = new Date(arrs[0], (arrs[1] - 1), arrs[2]);
            var ends = end.getTime();
            var weekDay = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
            //getDay() 方法可返回表示星期的某一天的数字。
            console.log("开始时间是" + weekDay[start.getDay()] + "\r\n" + "结束时间是" + weekDay[end.getDay()]);
            var now = new Date();
            console.log("现在是" + weekDay[now.getDay()]);
            if (starts >= ends)
                console.log('开始时间大于结束时间');
            else
                console.log('开始时间小于结束时间');
        }
        compareTime('2016-05-03', '2016-05-04');

其实关键就是getDay()函数返回值,返回值是0(周日)到6(周六)之间的一个整数。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant