Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment js to convert date from one format to other

Tags:

momentjs

I am using moment js to convert date variable format

moment("23MAY68", 'DDMMMYY').format('YYYY-MM-DD');
moment("23MAY99", 'DDMMMYY').format('YYYY-MM-DD');

Until the year 68, the output is 2068. From the year 69, the output is 1969 and not 2069. Is there a syntax or parameter in moment.js where I can mention it to use 2069 and not 1969?

http://plnkr.co/edit/ljXuskMsUAuJnpkqMPUn?p=preview

like image 914
firstpostcommenter Avatar asked Aug 12 '16 11:08

firstpostcommenter


2 Answers

From moment docs:

By default, two digit years above 68 are assumed to be in the 1900's and years 68 or below are assumed to be in the 2000's. This can be changed by replacing the moment.parseTwoDigitYear method.

So if you replace moment.parseTwoDigitYear in you code, you will have 2069 instead of 1969.

Here a working example:

moment.parseTwoDigitYear = function(year){
  return parseInt(year, 10) + 2000;
};

var s1 = moment("23MAY68", 'DDMMMYY').format('YYYY-MM-DD');
var s2 = moment("23MAY99", 'DDMMMYY').format('YYYY-MM-DD');

console.log(s1, s2);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
like image 182
VincenzoC Avatar answered Sep 28 '22 10:09

VincenzoC


Yes there is. Just parse with the correct format

moment("23MAY2099", 'DDMMMYYYY').format('YYYY-MM-DD');
like image 20
baao Avatar answered Sep 28 '22 09:09

baao