Convert dd-mm-yyyy string to date

2018-12-31 16:40发布

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?

12条回答
高级女魔头
2楼-- · 2018-12-31 17:08

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

查看更多
明月照影归
3楼-- · 2018-12-31 17:13

You can also write a date inside the parentheses of the Date() object, like these:

new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yyyy,mm,dd,hh,mm,ss)
new Date(yyyy,mm,dd)
new Date(milliseconds)
查看更多
无色无味的生活
4楼-- · 2018-12-31 17:17
new Date().toLocaleDateString();

simple as that, just pass your date to js Date Object

查看更多
柔情千种
5楼-- · 2018-12-31 17:20

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

查看更多
看淡一切
6楼-- · 2018-12-31 17:21

You can use an external library to help you out.

http://www.mattkruse.com/javascript/date/source.html

getDateFromFormat(val,format);

Also see this: Parse DateTime string in JavaScript

查看更多
临风纵饮
7楼-- · 2018-12-31 17:23

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.

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:

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

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)
}
查看更多
登录 后发表回答