I have a string with a date in it formatted like so: YYYYMMDDHHMMSS. I was wondering how I would convert it into a JavaScript Date object with JavaScript.
Thanks in advance!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
How about this for a wacky way to do it:
Zero external libraries, one line of code 😉
Explanation of the original method :
The
match()function (after it has beenslice()d to contain just the right) will return an array containing year, month, day, hour, minute, and seconds. This just happens to be the exact right order for the Date constructor.Function.applyis a way to call a function with the arguments in an array, so I usedDate.apply(<that array>).for example:
I’ve just now realised that this function doesn’t actually work, since javascript months are zero-indexed. You could still do it in a similar method, but there’d be an intermediate step, subtracting one from the array before passing it to the constructor. I’ve left it here, since it was asked about in the comments.
The other option works as expected however.