Convert dd-mm-yyyy string to date

后端 未结 14 1908
孤城傲影
孤城傲影 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 06:08
    var from = $("#datepicker").val(); 
    var f = $.datepicker.parseDate("d-m-Y", from);
    
    0 讨论(0)
  • 2020-11-22 06:10

    regular expression example:

    new Date( "13-01-2011".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );
    
    0 讨论(0)
  • 2020-11-22 06:11

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

    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:

    const toDate = (dateStr) => {
      const [day, month, year] = dateStr.split("-")
      return new Date(year, month - 1, day)
    }
    
    0 讨论(0)
  • 2020-11-22 06:14

    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

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

    The accepted answer kinda has a bug

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

    Consider if the datepicker contains "77-78-7980" which is obviously not a valid date. This would result in:

    var f = new Date(7980, 77, 77);
    => Date 7986-08-15T22:00:00.000Z
    

    Which is probably not the desired result.

    The reason for this is explained on the MDN site:

    Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1).


    A better way to solve the problem is:

    const stringToDate = function(dateString) {
      const [dd, mm, yyyy] = dateString.split("-");
      return new Date(`${yyyy}-${mm}-${dd}`);
    };
    
    console.log(stringToDate('04-04-2019'));
    // Date 2019-04-04T00:00:00.000Z
    
    console.log(stringToDate('77-78-7980'));
    // Invalid Date
    

    This gives you the possibility to handle invalid input.

    For example:

    const date = stringToDate("77-78-7980");
    
    if (date === "Invalid Date" || isNaN(date)) {
      console.log("It's all gone bad");
    } else {
      // Do something with your valid date here
    }
    
    0 讨论(0)
提交回复
热议问题