I’m trying to parse a date string like 15/03/2018 and turn it into a proper JavaScript Date object. The problem is I keep getting an error that says “dateString.split is not a function”.
Here’s what I’m attempting to do:
var dateString = 15/03/2018;
var segments = dateString.split("/");
var result = segments + '';
var finalDate = new Date(result[2], result[1] - 1, result[0]);
console.log(finalDate);
The input format is always day/month/year and I need to convert it to a Date object that JavaScript can work with. What am I doing wrong here?
You’re missing quotes around your date string. When you write var dateString = 15/03/2018;, JavaScript thinks it’s math division, not a string. Wrap it in quotes like var dateString = "15/03/2018"; so it actually has the split method. There’s another bug too - you’re using result instead of segments when creating the Date object. Should be var finalDate = new Date(segments[2], segments[1] - 1, segments[0]); because result becomes a string after concatenation and won’t give you the individual date parts you need.
You’re declaring a math expression instead of a string. JavaScript sees 15/03/2018 as division, which results in approximately 0.00248. Numbers don’t have a split method, leading to your error. Additionally, the way you’re handling the result variable is problematic. When you concatenate segments to a string with segments + '', you lose the structure and can’t index it as an array anymore. Instead, use the segments directly in your Date constructor without conversion.
your problem is 15/03/2018 without quotes - js treats this as division so u get a number, not a string. that’s why split() fails. just wrap it in quotes like "15/03/2018" and it’ll work.