Convert dd-mm-yyyy string to date

后端 未结 14 1912
孤城傲影
孤城傲影 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: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)
    }
    

提交回复
热议问题