Convert dd-mm-yyyy string to date

后端 未结 14 1941
孤城傲影
孤城傲影 2020-11-22 05:09

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          


        
相关标签:
14条回答
  • 2020-11-22 05:56

    You can just:

    var f = new Date(from.split('-').reverse().join('/'));
    
    0 讨论(0)
  • 2020-11-22 05:58

    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)
        );
    }
    
    0 讨论(0)
  • 2020-11-22 05:59

    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)
    
    0 讨论(0)
  • 2020-11-22 06:04

    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

    0 讨论(0)
  • 2020-11-22 06:05
    new Date().toLocaleDateString();
    

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

    0 讨论(0)
  • 2020-11-22 06:06

    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

    0 讨论(0)
提交回复
热议问题