Created
October 14, 2015 12:06
-
-
Save sylvainpolletvillard/0aa9df9c180cd007e5e1 to your computer and use it in GitHub Desktop.
valueAsDate polyfill
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if(!("valueAsDate" in HTMLInputElement.prototype)){ | |
Object.defineProperty(HTMLInputElement.prototype, "valueAsDate", { | |
get: function(){ | |
var d = this.value.split(/\D/); | |
return new Date(d[0], --d[1], d[2]); | |
}, | |
set: function(d){ | |
var day = ("0" + d.getDate()).slice(-2), | |
month = ("0" + (d.getMonth() + 1)).slice(-2), | |
datestr = d.getFullYear()+"-"+month+"-"+day; | |
this.value = datestr; | |
} | |
}); | |
} | |
// test & demo: http://jsbin.com/wumikawero/1/edit?html,js,output |
nice job
just needs:
- get and set to convert value of empty string to/from valueAsDate of null
- work in UTC date time
therefore becomes something like
Object.defineProperty(HTMLInputElement.prototype, "valueAsDate", {
get: function(){
if (this.value === '') { return null; }
const d = this.value.split('-');
return new Date(Date.UTC(Number(d[0]), Number(d[1]) - 1, Number(d[2])));
},
set: function(d){
if (d === null) {
this.value = '';
return;
}
const day = ('0' + d.getUTCDate()).slice(-2);
const month = ('0' + (d.getUTCMonth() + 1)).slice(-2);
this.value = d.getUTCFullYear() + '-' + month + '-' + day;
}
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice Job!