i am trying to convert a string in the format dd-mm-yyyy into a date object in JavaScript using the following:
var from = $("#datepicker").val();
var to = $("#datepickertwo").val();
var f = new Date(from);
var t = new Date(to);
("#datepicker").val()
contains a date in the format dd-mm-yyyy.
When I do the following, I get "Invalid Date":
alert(f);
Is this because of the '-' symbol? How can I overcome this?
Use this format:
myDate = new Date('2011-01-03'); // Mon Jan 03 2011 00:00:00
You can also write a date inside the parentheses of the
Date()
object, like these:simple as that, just pass your date to js Date Object
Another possibility:
Match the digits and reorder them
You can use an external library to help you out.
http://www.mattkruse.com/javascript/date/source.html
Also see this: Parse DateTime string in JavaScript
Split on "-"
Parse the string into the parts you need:
Use regex
Why not use regex?
Because you know you'll be working on a string made up of three parts, separated by hyphens.
However, if you were looking for that same string within another string, regex would be the way to go.
Reuse
Because you're doing this more than once in your sample code, and maybe elsewhere in your code base, wrap it up in a function:
Using as:
Or if you don't mind jQuery in your function:
Using as:
Modern JavaScript
If you're able to use more modern JS, array destructuring is a nice touch also: