javascript - Convert dd-mm-yyyy string to date -


i trying convert string in format dd-mm-yyyy date object in javascript using following:

 var = $("#datepicker").val();  var = $("#datepickertwo").val();  var f = new date(from);  var t = new date(to); 

("#datepicker").val() contains date in format dd-mm-yyyy. when following, "invalid date":

alert(f); 

is because of '-' symbol? how can overcome this?

parse string parts need:

var = $("#datepicker").val().split("-"); var f = new date(from[2], from[1] - 1, from[0]); 

why not use regex?

because know you'll working on string made of 3 parts, separated hyphens.

however, if looking same string within string, regex way go.

reuse

because you're doing more once in sample code, , maybe elsewhere in code base, wrap in function:

function todate(datestr) {     var parts = datestr.split("-");     return new date(parts[2], parts[1] - 1, parts[0]); } 

using as:

var = $("#datepicker").val(); var = $("#datepickertwo").val(); var f = todate(from); var t = todate(to); 

or if don't mind jquery in function:

function todate(selector) {     var = $(selector).val().split("-");     return new date(from[2], from[1] - 1, from[0]); } 

using as:

var f = todate("#datepicker"); var t = todate("#datepickertwo"); 

modern javascript

if you're able use more modern js, array destructuring nice touch also:

function todate(datestr) {     const [day, month, year] = datestr.split("-")     return new date(year, month - 1, day) } 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -