使用Javascript比较时间 [英] Comparing Time using Javascript

查看:143
本文介绍了使用Javascript比较时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个开始时间,开始日期和结束日期,结束时间在我的网页上。我需要确保如果开始日期和结束日期相等,那么结束时间必须大于开始时间,如果结束日期大于开始日期,然后用户能够进入任何时间。如何实现此验证?

I am having a start time,start date and end date,end time on my web page.I need to ensure that if the start date and end date is equal then the end time must be greater than start time and if end date is greater than start date then user can able to enter any time.How can I achieve this validation?

推荐答案

我会高度强烈建议您使用 Datejs 。这应该给你一个起点:

I would highly highly recommend something like Datejs. This should give you a starting point though:

// get the values from your form
var startDate = $('input[name=startDate]').val(),
    endDate = $('input[name=endDate]').val(),
    startTime = $('input[name=startTime]').val(),
    endTime = $('input[name=endTime]').val()

如果您决定使用Datejs,则应使用 Date.parse(startDate)从输入字段中解析值。查看入门指南如果您决定不要使用DateJs,可以将getTime()附加到startTime var。 (例如 - endTime.getTime()< startTime.getTime()

If you decide to use Datejs you should parse the values from the input field using Date.parse(startDate). Check out the Getting Started. If you decide not to use DateJs, you could append getTime() to the startTime var. (e.g. - endTime.getTime() < startTime.getTime())

var error = '';

// if the start date is after the end date
if (startDate > endDate){
    var error = error + 'Your start date is after your end date.';
}
// if the start date and end date are the same -- and end time is before the start time
else if(startDate == endDate && endTime < startTime){
    var error = error + 'Your end time is before your start time.';
};

// handle any errors
if(error.length){
   alert(error);
};

这篇关于使用Javascript比较时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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