Yafim Simanovsky Yafim Simanovsky - 2 months ago 16x
jQuery Question

Convert date string dd-mm-yy to moment.js valid date

The issue of converting from datepicker to moment.js has come up a lot of times in SO. Sadly, after trying about 10 different solutions proposed by various methods that I found here as well as online, I still haven't been able to successfully convert from datepicker to moment.js in the way that I want.

What I do is get the selected date in jQuery datepicker, and in this case

it at the end and get "27-7-2016" for example, as a datepicker date.

$( "#datepicker" ).datepicker({
dateFormat: "dd-mm-yy",
maxDate: 6,
minDate: 0,
onSelect: function(dateText){
startDate = dateText;
selectedTemp = dateText.split("-");
gap = moment(selectedTemp[2]+"-"+selectedTemp[1]+"-"+selectedTemp[0]).fromNow();'


In the
variable, I have a moment object which gives me something like "in 10 hours" or "in 2 days". I later parse that string to a number to know in how many days the selected date is going to be:

gap = parseInt(gap);

I want to increment the date from datepicker by 2 days for example, that is go from "27-7-2016" to "29-7-2016" using the 2 days gap that I found.
So far this has always resulted in either me getting a whole moment.js object, or some error such as invalid, or the
method doesn't work etc. etc.

I also want to take the resultant "29-7-2016" and convert it to "2016-7-29", but since it's not a string I can't find a way to do that, and always run into formatting problems.



The fromNow() method return a string, not a moment object. If you want to calculate difference between now and the selected date you can use diff.

One you have a moment object, you can use add to modify it. Note that add modifies moment original object.

Using format you can get a string that represents the moment object in the format you prefer.

Hope that the following example helps to understand how you can use moment:

$( "#datepicker" ).datepicker({
   dateFormat: "dd-mm-yy",
   maxDate: 6,
   minDate: 0,
   onSelect: function(dateText){
     // Parse the selected string into moment object
     var momDate = moment(dateText, 'DD-MM-YYYY');
     // Get gap string
     // gap can be something like 'in 10 hours'
     var gap = momDate.fromNow();
     // Get difference as integer
     var gapInt = momDate.diff(moment().startOf('d'), 'd');
     // Here you can use add() to modify you moment object
     momDate.add(gapInt, 'days');
     // Get date formatted as you like
     var dateFormatted = momDate.format('YYYY-M-DD');
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

<input id="datepicker" type="text">