简体   繁体   中英

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. However when I try to parseInt(09) it returns NaN. I even added the radix 10, but that didn't work too.

Can you help me with this?

Thank you!

Use 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

 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 .

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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