Convert dd-mm-yyyy string to date

Convert dd-mm-yyyy string to date

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”:

Is this because of the ‘-‘ symbol? How can I overcome this?


Solution 1:

Split on “-“

Parse the string into the parts you need:

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

Use regex

var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))

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.


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:

function toDate(dateStr) {
  var parts = dateStr.split("-")
  return new Date(parts[2], parts[1] - 1, parts[0])

Using as:

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

Or if you don’t mind jQuery in your function:

function toDate(selector) {
  var from = $(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

Related:  react-router (v4) how to go back?

If you’re able to use more modern JS, array destructuring is a nice touch also:

function toDate(dateStr) {
  const [day, month, year] = dateStr.split("-")
  return new Date(year, month - 1, day)

Solution 2:

regular expression example:

new Date( "13-01-2011".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );

Solution 3:

Another possibility:

var from = "10-11-2011"; 
var numbers = from.match(/\d+/g); 
var date = new Date(numbers[2], numbers[0]-1, numbers[1]);

Match the digits and reorder them

Solution 4:

var from = $("#datepicker").val(); 
var f = $.datepicker.parseDate("d-m-Y", from);

Solution 5:

Using moment.js example:

var from = '11-04-2017' // OR $("#datepicker").val();
var milliseconds = moment(from, "DD-MM-YYYY").format('x');
var f = new Date(milliseconds)

Solution 6:

Use this format: myDate = new Date('2011-01-03'); // Mon Jan 03 2011 00:00:00