/**
* This function helps to autocomplete the date format MMDDYYY
* Converts M to 0M and MMD to MM0D. Ex. `1/` to `01/`, `01/1/` to `01/01/`
* Adds slash for MM and MMDD Ex. `01` to `01/`, `01/02` to `01/02/`
* Converts YY to YYYY. Ex. `01/01/01` to `01/01/2001`
*
* @param {String} str
* @return {String}
*/
var autocompleteMMDDYYYYDateFormat = function (str) {
str = str.trim();
var matches, year,
looksLike_MM_slash_DD = /^(\d\d\/)?\d\d$/,
looksLike_MM_slash_D_slash = /^(\d\d\/)?(\d\/)$/,
looksLike_MM_slash_DD_slash_DD = /^(\d\d\/\d\d\/)(\d\d)$/;
if( looksLike_MM_slash_DD.test(str) ){
str += "/";
}else if( looksLike_MM_slash_D_slash.test(str) ){
str = str.replace( looksLike_MM_slash_D_slash, "$10$2");
}else if( looksLike_MM_slash_DD_slash_DD.test(str) ){
matches = str.match( looksLike_MM_slash_DD_slash_DD );
year = Number( matches[2] ) < 20 ? "20" : "19";
str = String( matches[1] ) + year + String(matches[2]);
}
return str;
};
What REALLY is Data Science? Told by a Data Scientist - By Joma Tech
Writing perfect code is a challenging process. That's where code reviews come in to help…
"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"
"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"
My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…
View Comments
There's no validation for value of MM and DD? I can enter 99/99/ for MM and DD. Year is not a problem though I can also enter 19999999999
Validating for value of MM and DD weren't apart of the requirements when I wrote this. So that's why the user can enter invalid months and days.
Also I didn't included it because it would make the regular expressions harder to read.
Something like this.
var autocompleteMMDDYYYYDateFormat = function (str) {
str = (str ? String(str).replace(/^s+|s+$/g, "") : "");
var matches, YY,
looksLike_MM_slash_DD = /^((0d)|(1[012]))?([012]d|3[01])$/,
looksLike_MM_slash_D_slash = /^((0d)|(1[012]))?(d/)$/,
looksLike_MM_slash_DD_slash_YY = /^(dd/dd/)(dd)$/;
if (looksLike_MM_slash_DD.test(str)) {
str += "/";
} else if (looksLike_MM_slash_D_slash.test(str)) {
str = str.replace(looksLike_MM_slash_D_slash, "$10$2");
} else if (looksLike_MM_slash_DD_slash_YY.test(str)) {
matches = str.match(looksLike_MM_slash_DD_slash_YY);
YY = parseInt(matches[2], 10);
if (YY != 19 && YY != 20) {
YY = YY < 30 ? "20" : "19";
str = String(matches[1]) + YY + String(matches[2]);
}
}
return str;
};
Thanks, i create autoformat for MYSQL format
Check out http://jsfiddle.net/ot5c9obp/
Cool. It seems like a little bit buggy though. Matching `matchYmdhi` adds a `:` at the end.
Thanx Larry, you helped me a lot with your post.