Skip to content

Instantly share code, notes, and snippets.

@sylvainpolletvillard
Created October 14, 2015 12:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sylvainpolletvillard/0aa9df9c180cd007e5e1 to your computer and use it in GitHub Desktop.
Save sylvainpolletvillard/0aa9df9c180cd007e5e1 to your computer and use it in GitHub Desktop.
valueAsDate polyfill
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
@AskYous
Copy link

AskYous commented Feb 16, 2017

Nice Job!

@mcshaz
Copy link

mcshaz commented Dec 17, 2019

nice job
just needs:

  1. get and set to convert value of empty string to/from valueAsDate of null
  2. 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