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 16:59

Take a look at Datejs for all those petty date related issues.. You could solve this by parseDate function too

查看更多
十年一品温如言
3楼-- · 2018-12-31 17:00
var from = $("#datepicker").val(); 
var f = $.datepicker.parseDate("d-m-Y", from);
查看更多
宁负流年不负卿
4楼-- · 2018-12-31 17:02

In my case

new Date("20151102034013".replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, "$1-$2-$3T$4:$5:$6"))

Result: Mon Nov 02 2015 04:40:13 GMT+0100 (CET) then I use .getTime() to work with milliseconds

查看更多
唯独是你
5楼-- · 2018-12-31 17:02

You could use a Regexp.

var result = /^(\d{2})-(\d{2})-(\d{4})$/.exec($("#datepicker").val());
if (result) {
    from = new Date(
        parseInt(result[3], 10), 
        parseInt(result[2], 10) - 1, 
        parseInt(result[1], 10)
    );
}
查看更多
何处买醉
6楼-- · 2018-12-31 17:08

regular expression example:

new Date( "13-01-2011".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );
查看更多
素衣白纱
7楼-- · 2018-12-31 17:08

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