I want to convert 20170603 into a date. I want to use the function new Date(2017,06,03), but how do I extract the numbers from the date? I tried using
new Date(parseInt(startDate.substr(0,4)), parseInt(startDate.substr(5,6)) -1, parseInt(startDate.substr(6,8)))
However, this gives me very weird values. How do I extract the exact numbers into the Date function?
I want to convert 20170603 into a date. I want to use the function new Date(2017,06,03), but how do I extract the numbers from the date? I tried using
new Date(parseInt(startDate.substr(0,4)), parseInt(startDate.substr(5,6)) -1, parseInt(startDate.substr(6,8)))
However, this gives me very weird values. How do I extract the exact numbers into the Date function?
Share Improve this question asked Jul 14, 2017 at 3:21 user2896120user2896120 3,2828 gold badges46 silver badges109 bronze badges 5-
You want to use
slice
instead ofsubstr
. And better pass10
as a base toparseInt
– Bergi Commented Jul 14, 2017 at 3:31 -
@Bergi As much as I wanted to advise
*1
instead ofparseInt()
due to base conversion issues, I could not conceive of a situation (for legal dates) where this will fail. Can you? – Phrogz Commented Jul 14, 2017 at 3:33 -
@Phrogz Year
0999
:-) Yeah, it's unlikely to fail, but that's not a reason not to apply the best practise – Bergi Commented Jul 14, 2017 at 3:34 -
Is
20170603
a number or a string? – guest271314 Commented Jul 14, 2017 at 3:36 -
2
There's no need for conversion to number at all, the first thing that the Date constructor does when passed two or more arguments is to run ToNumber of each of the values. Also,
startDate.substr(5,6) -1
will produce a number anyway, so that value is already a number. A radix for base 10 hasn't been necessary since ECMAScript ed 5. – RobG Commented Jul 14, 2017 at 3:37
4 Answers
Reset to default 4Second parameter of substr
function is length of string you want to extract;
new Date(parseInt(startDate.substr(0,4)),
parseInt(startDate.substr(4,2)) - 1,
parseInt(startDate.substr(6,2)));
substr Method (String) (JavaScript)
Using replace()
with RegExp
const date_str = "20170603";
console.log( new Date( date_str.replace( /(\d{4})(\d{2})(\d{2})/, "$1/$2/$3" ) ) );
Slicing by character counts:
new Date(my_str.match(/(....)(..)(..)/).slice(1,4).join('/'))
If using an external library is not an issue. I would suggest using moment.js
There are many methods available. For your case.
var d = new moment("20170603 ", "YYYYMMDD").toDate();
I am using this lib to solve a lot of challenges.