<html>
<head>
<title>JavaScript计算两个时间差</title>
<meta http-equiv="content-Type" content="text/html;charset=gb2312">
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function isValidDate(dateStr) {
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; // requires 4 digit year
var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
alert(dateStr + " Date is not in a valid format.")
return false;
}
month = matchArray[1];
day = matchArray[3];
year = matchArray[4];
if (month < 1 || month > 12) {
alert("Month must be between 1 and 12.");
return false;
}
if (day < 1 || day > 31) {
alert("Day must be between 1 and 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("Month "+month+" doesn't have 31 days!")
return false;
}
if (month == 2) {
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
alert("February " + year + " doesn't have " + day + " days!");
return false;
   }
}
return true;
}
function isValidTime(timeStr) {
var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
var matchArray = timeStr.match(timePat);
if (matchArray == null) {
alert("Time is not in a valid format.");
return false;
}
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];
if (second=="") { second = null; }
if (ampm=="") { ampm = null }
if (hour < 0  || hour > 23) {
alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
return false;
}
if (hour <= 12 && ampm == null) {
if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
alert("You must specify AM or PM.");
return false;
   }
}
if  (hour > 12 && ampm != null) {
alert("You can't specify AM or PM for military time.");
return false;
}
if (minute < 0 || minute > 59) {
alert ("Minute must be between 0 and 59.");
return false;
}
if (second != null && (second < 0 || second > 59)) {
alert ("Second must be between 0 and 59.");
return false;
}
return true;
}
function dateDiff(dateform) {
date1 = new Date();
date2 = new Date();
diff  = new Date();
if (isValidDate(dateform.firstdate.value) && isValidTime(dateform.firsttime.value)) { // Validates first date
date1temp = new Date(dateform.firstdate.value + " " + dateform.firsttime.value);
date1.setTime(date1temp.getTime());
}
else return false;
if (isValidDate(dateform.seconddate.value) && isValidTime(dateform.secondtime.value)) { // Validates second date
date2temp = new Date(dateform.seconddate.value + " " + dateform.secondtime.value);
date2.setTime(date2temp.getTime());
}
else return false;
diff.setTime(Math.abs(date1.getTime() - date2.getTime()));
timediff = diff.getTime();
weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
timediff -= weeks * (1000 * 60 * 60 * 24 * 7);
days = Math.floor(timediff / (1000 * 60 * 60 * 24));
timediff -= days * (1000 * 60 * 60 * 24);
hours = Math.floor(timediff / (1000 * 60 * 60));
timediff -= hours * (1000 * 60 * 60);
mins = Math.floor(timediff / (1000 * 60));
timediff -= mins * (1000 * 60);
secs = Math.floor(timediff / 1000);
timediff -= secs * 1000;
dateform.difference.value = weeks + " weeks, " + days + " days, " + hours + " hours, " + mins + " minutes, and " + secs + " seconds";
return false;
}
//  End -->
</script>
<form onSubmit="return dateDiff(this);">
<table>
<tr><td>
<pre>
起始时间:Date:<input type=text name=firstdate value="" size=10 maxlength=10>(MM/DD/YYYY format)
          Time:<input type=text name=firsttime value="" size=10 maxlength=10>(HH:MM:SSam/pm format)
结束日期:Date:<input type=text name=seconddate value="" size=10 maxlength=10>(MM/DD/YYYY format)
          Time:<input type=text name=secondtime value="" size=10 maxlength=10>(HH:MM:SSam/pm format)
<center>
<input type=submit value="计算日期之差"><br>
日期之差为:<input type=text name=difference value="" size=50>
</center>
</pre>
</td></tr>
</table>
</form>
</body>
</html>

JavaScript获取两个时间的时间差的更多相关文章

  1. C#两个时间的时间差的方法

    今天遇到一问题,计算两个时间的时间差,看网上的写法较为复杂,找到个简单点的,记录下作为自己的总结. 关键函数: DateTime.Subtract 函数解释: 从此实例中减去指定的日期和时间,返回一个 ...

  2. java中获取两个时间中的每一天

    引入下面方法即可: /** * 获取两个时间中的每一天 * @param bigtimeStr 开始时间 yyyy-MM-dd * @param endTimeStr 结束时间 yyyy-MM-dd ...

  3. PHP 获取两个时间之间的月份

    ## 获取两个时间之间的间距时间 $s = '2017-02-05'; $e = '2017-07-20'; $start = new \DateTime($s); $end = new \DateT ...

  4. JS比较两个时间的时间差

    /** * 比较两个时间的时间差 * @param startTime 开始时间 * @param endTime 结束时间 * @demo compareTime(new Date('2019-12 ...

  5. C#计算两个时间的时间差,精确到年月日时分秒

    喏,计算两个时间的时间差,精确到年月日时分秒 看起来比较笨的方法了,不知道有没有改进 DateTime d1 = new DateTime(2016, 4, 1, 0, 0, 0); DateTime ...

  6. 获取两个时间点间的随机时间&时间戳

    获取两个时间点间的随机时间&时间戳 方案一 # python2 不兼容,python3正常 import datetime,random def randomtimes(start, end, ...

  7. JavaScript获取两个数之间的任意随机数

    通过JavaScript的Math.random()方法可以获取0到1之间的任意随机数,那如何获取任意给定的两个数之间的随机数呢?如获取2和5之间的随机数,5和10之间的随机数等. 由于Math.ra ...

  8. 获取两个时间节点的月份列表&&每个月份的开始时间及结束时间

    //Q:从今天起之前五个月的列表 date_default_timezone_set('PRC'); $time=strtotime('-5 month'); //包含本月 $begin = strt ...

  9. GoLang 获取两个时间相差多少小时

    package main import ( "fmt" "time" ) func main() { fmt.Println(getHourDiffer(&qu ...

随机推荐

  1. cocos2d-x 二进制文件的读写

    转自:http://blog.csdn.net/wolfking_2009/article/details/10616069 cocos2d-x里面的二进制文件读取的方法是有的,作者对方法封装了下,将 ...

  2. C++ Interview - using new and delete to alloc and free memory

    1. dynamic create object and initialization int *pi = new int; // pi points to an uninitialized int ...

  3. bzoj 2435: [Noi2011]道路修建 树上 dp

    2435: [Noi2011]道路修建 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://www.lydsy.com/JudgeOnline/pr ...

  4. Google Map和桌面组件 Android开发教程

    本文节选于机械工业出版社推出的<Android应用开发揭秘>一 书,作者为杨丰盛.本书内容全面,详细讲解了Android框架.Android组件.用户界面开发.游戏开发.数据存储.多媒体开 ...

  5. windows下如何github ssh 公钥

    windows下如何github ssh 公钥   1. 安装git,从程序目录打开 "Git Bash"  2. 键入命令:ssh-keygen -t rsa -C " ...

  6. MySQL通用优化 叶金荣!!!

    http://mp.weixin.qq.com/s?__biz=MjM5NDE0MjI4MA==&mid=208777870&idx=1&sn=6efddd6283e4deb3 ...

  7. 无需图片,使用CSS3实现圆角按钮[转]

    首先来看看效果:   事例HTML代码: <a href="#" class="button green">button</a> < ...

  8. archlinux locale-gen 命令出错

    如果运行locale-gen命令出现以下的错误“locale alias file `/usr/share/locale/locale.alias' not found: No such file o ...

  9. web开发下的各种下载方法

    利用TransmitFile方法,解决Response.BinaryWrite下载超过400mb的文件时导致Aspnet_wp.exe进程回收而无法成功下载的问题. 代码如下: Response.Co ...

  10. Doing Homework 状态压缩DP

    Doing Homework 题目抽象:给出n个task的name,deadline,need.  每个任务的罚时penalty=finish-deadline;   task不可以同时做.问按怎样的 ...