将字符串转换为JavaScript(h:m) [英] Convert string to time JavaScript (h:m)

查看:119
本文介绍了将字符串转换为JavaScript(h:m)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的朋友和我正在做一个学校的项目;任务是做一个房间预订站点。
这是我们第一年尝试JavaScript,我们希望将一个字符串格式化为时间(h:m)。
我们的房间预订网站的用户可以选择他/她想要房间的那一天的时间,输出是:H:m(24小时:分钟)。
例如12:15。



因此我的问题是:
有可能将这个字符串(h:m)转换成时间,很容易检查用户是否输入超过30分钟的预订时间?所以我们可以这样说:

  if(start_of_reservation< start_of_reservation(+ 30 minutes)){
alert您需要预订房间至少30分钟); }

else if(start_of_reservation> start_of_reservation(+ 6hours)){
alert(你不能预订超过6个小时的房间); }

else {
//移动..
}


解决方案

  var year ='2013'; 
var month ='04';
var day ='18';

var hours ='12';
var min ='35';

var reserv = new Date(year,month,day,hour,min)

console.log(reserv);

您可能希望通过检查当前日期为自己获取的年,月和日值。这纯粹是为了显示如何将字符串转换为日期。



使用 reserv.getTime()转换到毫秒的时间,因此能够比较两次;

  reserv.getTime() -  reserv2.getTime()

有关详细信息,请查看 MDN


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.

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:

 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..
 }

解决方案

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() - reserv2.getTime()

For more information, check the MDN.

这篇关于将字符串转换为JavaScript(h:m)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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