Elliot Starks Elliot Starks - 23 days ago 7
HTML Question

Parsing Date String Using Moment.js Incorrectly Returns Unix Timestamp

I'm attempting to parse a Javascript date from an html attribute using Moment.js.
I'm utilizing the

moment(String, String)
function to pass in a format string, but I'm getting what looks like a Unix timestamp returned. What am I missing here? Thanks!



var from = $('#requested-from').attr('data-requested-from');
console.log('from: ' + from);

var requestedFrom = moment(from, 'MM-DD-YYYY');
console.log('requestedFrom: ' + requestedFrom);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="requested-from" class="hidden" data-requested-from=06-10-2017></span>




Answer

You need to format() the moment however you like. MomentJS returns the timestamp as a default.

var from = $('#requested-from').attr('data-requested-from');
console.log('from: ' + from);

var requestedFrom = moment(from, 'MM-DD-YYYY');
console.log('requestedFrom: ' + requestedFrom.format('MM-DD-YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="requested-from" class="hidden" data-requested-from=06-10-2017></span>