jQuery 将字符串转换为时间 JavaScript (h:m)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16072056/
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
Convert string to time JavaScript (h:m)
提问by Mr.Turtle
My friend and I are doing a school project; the task is to make a room-reservation-site. This is our first year trying JavaScript, and we want a string to be formatted into time (h:m). The user of our room-reservation-site can choose what time of the day he/she wants the room, and the output is: H:m (24hour-clock:minutes). For example 12:15.
我和我的朋友正在做一个学校项目;任务是制作一个房间预订网站。这是我们第一年尝试 JavaScript,我们希望将字符串格式化为时间 (h:m)。我们房间预订网站的用户可以选择他/她想要房间的时间,输出为:H:m(24 小时制:分钟)。例如 12:15。
Therefor my question is: Is there possible to convert this string (h:m) into time, and easily check if the user typed more than 30minutes of booking-time? So we can for example say:
因此我的问题是:是否可以将此字符串 (h:m) 转换为时间,并轻松检查用户是否输入了超过 30 分钟的预订时间?例如,我们可以说:
if(start_of_reservation < start_of_reservation(+30minutes)){
alert("You need to book a room atleast 30minutes"); }
else if(start_of_reservation > start_of_reservation(+6hours)){
alert("You can't book a room longer than 6 hours"); }
else {
// moving on..
}
回答by
var year = '2013';
var month = '04';
var day = '18';
var hour = '12';
var min = '35';
var reserv = new Date(year,month,day,hour,min)
console.log(reserv);
Those year, month and day values you might want to fetch for yourselves by checking the current date. This is purely to show how to convert the string into a date.
您可能希望通过检查当前日期为自己获取那些年、月和日值。这纯粹是为了展示如何将字符串转换为日期。
Use reserv.getTime()
to convert to milliseconds time and thus being able to compare two times;
使用reserv.getTime()
转换到毫秒的时间,从而能够比较两个时间;
reserv.getTime() - reserv2.getTime()
For more information, check the MDN.
有关更多信息,请查看MDN。
回答by Brian McCutchon
Yes. Use regular expressionsand the Date object.
RegExps would be used to extract hours and minutes from the date string,
RegExps 将用于从日期字符串中提取小时和分钟,
and the Date object would be used for comparisons.
并且 Date 对象将用于比较。