Javascript jquery从字符串到时间的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7301449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:41:37  来源:igfitidea点击:

jquery convertion from string to time

javascriptstringtime

提问by sisko

I have a system in development which records various times of the day in the following format: 06:53:22or 19:23:58as examples.

我有一个正在开发的系统,它以以下格式记录一天中的不同时间: 例如 06:53:2219:23:58

Can anyone tell me if it is possible to convert this string into javascript construct which I can use to compare times of the day?

谁能告诉我是否可以将此字符串转换为 javascript 构造,我可以用它来比较一天中的时间?

回答by Arnaud Le Blanc

You can parse the time with this:

你可以用这个解析时间:

function timeToSeconds(time) {
    time = time.split(/:/);
    return time[0] * 3600 + time[1] * 60 + time[2];
}

It returns a number of seconds since 00:00:00, so you can compare the results easily:

它返回自 00:00:00 以来的秒数,因此您可以轻松比较结果:

timeToSeconds('06:53:22') < timeToSeconds('19:23:58')

回答by Joseph Marikle

var startTime = "19:23:58";
var endTime = "06:53:22";

var startDate = new Date("1/1/1900 " + startTime);
var endDate = new Date("1/1/1900 " + endTime);

if (startDate > endDate)
  alert("invalid time range");
else
  alert("valid time range");

js is smart enough to figure it out :)

js 足够聪明,可以弄清楚:)

回答by Aleksey Savitsky

of course you can do it, but before you should parse this string. date = new Date(year, month, day, hours, minutes, seconds, milliseconds)- we creaeted new object. After we can use date.getTime()date.getFullYear..

当然你可以这样做,但在你应该解析这个字符串之前。 date = new Date(year, month, day, hours, minutes, seconds, milliseconds)- 我们创建了新对象。在我们可以使用date.getTime()date.getFullYear..