Converting (formatting) a 2-digit date to a 4-digit date

I'm having trouble correctly formatting two-digit dates as 4-digit dates.

I have an input text box:

<input type="text" value="" class="date"/> 

And then I want to format it in the format "mm / dd / yyyy" after the user enters the date. Therefore, I have an onChange event:

 $('.date').on('change',function(){ var date = new Date($(this).val()); $(this).val((date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear()); }); 

Ok, now weirdness comes (I will use 12/12/12 as an example):

1) getFullYear () returns 1912 in all IE, FF. Chrome returns in 2012.

2) getYear () returns 112 in IE, Chrome. FF returns 12.

Thus, it seems that the only option at the moment is to sniff the user agent and use it accordingly. Anyway, sniffs UA?

+4
source share
3 answers

you can try, first, to separate the input parts

 ... var input=$(this).val(); var month=input.substr(0,2)-1; var day=input.substr(3,2); var year=parseInt("20"+ input.substr(6,2)); 

and then run the new Date object:

 var date= new Date(year,month,day); 

or write it back to the field, as you did:

 $(this).val((date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear()); 
+1
source

After the request, I ended up using Moment.js . I tried date.js , but since I partially work with unix timestamps, it seems that this moment is doing better (IMO).

0
source

Using moment.js :

 const moment = require("moment") const date = moment("21", "YY") const year = date.format("YYYY") 
0
source

All Articles