[英]How to convert double digit string to int in Javascript?
In my project, I have a table that represents a schedule.在我的项目中,我有一个代表时间表的表格。 In first column I have info about time (hours:minutes)
在第一列中,我有关于时间的信息(小时:分钟)
I'm trying to extract the text from one cell and split it into hours and minutes, because I'll use them to create a Date object.我正在尝试从一个单元格中提取文本并将其拆分为小时和分钟,因为我将使用它们来创建日期 object。 However when I try to
parseInt(09)
it returns NaN.但是,当我尝试
parseInt(09)
时,它返回 NaN。 I even added the radix 10, but that didn't work too.我什至添加了基数 10,但这也没有用。
Can you help me with this?你能帮我解决这个问题吗?
Thank you!谢谢!
Use split
:使用
split
:
var time = "17:30"; var hours = time.split(":")[0]; var minutes = time.split(":")[1]; console.log("hours: " + hours); console.log("minutes: " + minutes);
Hey your example should work, but seems like you don't pass a string to parseInt, I belive that you have those times as string which you can parse like this嘿,你的例子应该可以工作,但似乎你没有将字符串传递给 parseInt,我相信你有那些时间作为字符串,你可以像这样解析
const time = "10:30" const split = time.split(":") const hours = parseInt(split[0], 10) const minutes = parseInt(split[1], 10) console.log(hours, minutes)
use code:使用代码:
var time = "13:30";
var hours = time.split(":")[0];
var minutes = time.split(":")[1];
You can do it by using split
, map
and Bit shifting
.您可以通过使用
split
、 map
和Bit shifting
来做到这一点。
const timeStr = "09:30"; const [hour, min] = timeStr.split(':').map(item => item >> 0); console.log(hour, min);
The code item => item >> 0
means it takes the split value and it executes a zero bit right shifting returns a 32 bit number.代码
item => item >> 0
表示它采用拆分值并执行零位右移返回一个 32 位数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.