Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Split on "-"</strong></p> <p>Parse the string into the parts you need:</p> <pre><code>var from = $("#datepicker").val().split("-") var f = new Date(from[2], from[1] - 1, from[0]) </code></pre> <p><strong>Use regex</strong></p> <pre><code>var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3")) </code></pre> <p><strong>Why not use regex?</strong></p> <p>Because you know you'll be working on a string made up of three parts, separated by hyphens.</p> <p>However, if you were looking for that same string within another string, regex would be the way to go.</p> <p><strong>Reuse</strong></p> <p>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:</p> <pre><code>function toDate(dateStr) { var parts = dateStr.split("-") return new Date(parts[2], parts[1] - 1, parts[0]) } </code></pre> <p>Using as:</p> <pre><code>var from = $("#datepicker").val() var to = $("#datepickertwo").val() var f = toDate(from) var t = toDate(to) </code></pre> <p>Or if you don't mind jQuery in your function:</p> <pre><code>function toDate(selector) { var from = $(selector).val().split("-") return new Date(from[2], from[1] - 1, from[0]) } </code></pre> <p>Using as:</p> <pre><code>var f = toDate("#datepicker") var t = toDate("#datepickertwo") </code></pre> <p><strong>Modern JavaScript</strong></p> <p>If you're able to use more modern JS, array destructuring is a nice touch also:</p> <pre><code>function toDate(dateStr) { const [day, month, year] = dateStr.split("-") return new Date(year, month - 1, day) } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload