简体   繁体   English

使用javascript的时差

[英]Time difference using javascript

What would be the code for finding the time difference between two different times which are in a 12hr format using javascript. 什么是使用javascript找到12小时格式的两个不同时间之间的时差的代码。 I am using these two time fields in my dynamic gridview . 我在动态gridview中使用这两个时间字段。

 var gridNew = document.getElementById("<%= Gridview1.ClientID %>");
            if (gridNew.rows.length > 0) {
                for (i = 0; i < gridNew.rows.length - 2; i++) {
                    var frombox = document.getElementById("Gridview1_txtFrom_" + (i));
                    var tobox = document.getElementById("Gridview1_txtTo_" + (i));
                      if(frombox.value<=tobox.value){
                        alert("Enter valid time set");
                        return false;

Here' how you can get milliseconds time difference between two custom dates. 这里'你如何在两个自定义日期之间获得毫秒时差。

Math.abs(new Date(firstDateString).getTime() - new Date(secondDateString).getTime());

If you have problems parsing/converting to Date , consider using a library like date.js or moment.js 如果您在解析/转换为Date遇到问题,请考虑使用date.js或moment.js等库

With moment you could do something like this: 随着时间你可以做这样的事情:

var diff = moment('3:30','HH:mm').diff(moment('3:20','HH:mm'));

If you need am / pm: 如果你需要上午/下午:

var diff = moment('3:30 pm','HH:mm a').diff(moment('3:20 am','HH:mm a'));

Here's jsfiddle 这是jsfiddle

Times in JS can be a pain to deal with cross browser, and anyone who has had to debug wierd cross browser behavior can attest to. JS中的时代对于处理跨浏览器来说可能是一种痛苦,任何不得不调试错误的跨浏览器行为的人都可以证明这一点。 I have learned than when ever i wanna do anything with dates in JS involve the moment.js lib. 我学到了比以往任何时候我都想做任何关于JS的日期涉及到moment.js lib。

I was reluctant at first as I thought i can just do most everything myself and roll my own. 起初我不情愿,因为我认为我可以自己做大部分事情而且自己动手。 This is a cuban cigar and no amount of home rolling can cover all the tools moment comes with. 这是一支古巴雪茄,没有多少家用滚动可以涵盖所有工具的时刻。

I wont tell you how to fix, just give you the tool... 我不会告诉你如何解决,只是给你工具......

moment().diff 矩()。DIFF

Enjoy! 请享用!

You haven't shown the format of the times other than to say they're in "12hr format". 除了说它们是“12hr格式”之外,您还没有显示时间格式。 An algorithm is to parse and convert them to a common unit, say seconds, find the difference, then format it back into whatever units suit. 一种算法是解析并将它们转换为一个公共单位,比如秒,找到差异,然后将其格式化回任何适合的单位。

So if the times are in h:m:sa/p format like "9:42:15 am" and you want the result in a similar format, then the following functions may help. 因此,如果时间是h:m:sa / p格式,如“9:42:15 am”,并且您希望结果采用类似的格式,那么以下函数可能会有所帮助。

 /* Convert time in h:m:sa/p format to seconds ** Seconds component is optional, h:m is OK ** Tolerates space before am/pm, leading and trailing whitespace ** Doesn't validate string ** ** @param {string} s - time to parse ** @returns {number} time converted to seconds. */ function hmsToSeconds(s) { var b = s.match(/\\d+/g); var am = /am\\s*$/i.test(s); return ((b[0] % 12) + (am? 0:12))*3600 + (b[1]*60) + (+b[2]||0); } /* Convert seconds to time in h:mm:ss format ** Maintains sign of input (+/-). ** ** @param {number} s - seconds to convert ** @returns {string} seconds converted to h:mm:ss. */ function secToHMS(s) { function z(n){return (n<10? '0' : '') + n} var sign = s < 0? '-' : ''; s = Math.abs(s); return sign + (s/3600 | 0) + ':' + z((s%3600 / 60 |0)) + ':' + z(s%60); } function getTimeDifference(t0, t1) { return secToHMS(hmsToSeconds(t1) - hmsToSeconds(t0)); } document.write(getTimeDifference('11:32 am','12:38:51pm')); 

Try this simple plugin to get time differences. 试试这个简单的插件来获得时差。

https://github.com/gayanSandamal/good-time https://github.com/gayanSandamal/good-time

import the goodTimeDiff method from good-time.js to your project 将goodTimeDiff方法从good-time.js导入到您的项目中

import {goodTimeDiff} from './scripts/good-time.js'

declare an object to give settings like below. 声明一个对象以提供如下设置。 let settings = {} 设置= {}

now assign time values to the declared object variable. 现在为声明的对象变量分配时间值。 *time must be in standard format and must be a string! *时间必须是标准格式,必须是字符串! * 'from' is optional the default value will be the browser current time. * 'from'是可选的,默认值将是浏览器当前时间。

let settings = {
    'from': '2019-01-13T00:00:29.251Z',
    'to': '2018-09-22T17:15:29.251Z'
}

now calllback the method called goodTimeDiff() and pass the settings object variable as a parameter. 现在calllback名为goodTimeDiff()的方法,并将设置对象变量作为参数传递。

goodTimeDiff(settings)

Finally assign the method to any variable you want. 最后将方法分配给您想要的任何变量。

let lastCommentedTime = goodTimeDiff(timeSettings)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM