Reputation: 69
I need to use the Date
object for three different purposes, can I do this as follows?
I am very new to JavaScript, so I am not sure if the following define is OK for all the browsers.
Date.prototype.yyyymmdd = function()
{
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return yyyy+"-" + (mm[1]?mm:"0"+mm[0])+"-" + (dd[1]?dd:"0"+dd[0]);
};
Date.prototype.mmddyyyy = function()
{
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return (mm[1]?mm:"0"+mm[0])+"-" + (dd[1]?dd:"0"+dd[0])+"-" + yyyy;
};
Date.prototype.mmdd = function()
{
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return (mm[1]?mm:mm[0])+"/" + (dd[1]?dd:dd[0]);
};
var d0 = new Date();
console.log(d0.mmddyyyy);
var d1 = new Date();
console.log(d1.yyyymmdd);
var d2 = new Date();
console.log(d2.mmdd);
Upvotes: 2
Views: 1159
Reputation: 178350
You just missed the brackets - it should run in any browser (but will currently fail if console is not supported or in IE8, open)
var d0 = new Date();
console.log(d0.mmddyyyy());
var d1 = new Date();
console.log(d1.yyyymmdd());
var d2 = new Date();
console.log(d2.mmdd());
I would personally prefer one prototype
DEMO:
Date.prototype.formatDate=function(fmt) {
fmt = fmt || "yyyymmdd";
var yyyy = this.getFullYear();
var mm = this.getMonth()+1;
if (mm<10) mm="0"+mm;
var dd = this.getDate();
if (dd<10) dd="0"+dd;
if (fmt==="yyyymmdd") return yyyy+"-" + mm+"-" + dd;
if (fmt==="mmddyyyy") return ""+mm+"-" + dd +"-" + yyyy;
if (fmt==="mmdd") return ""+mm+"/"+dd;
};
var d0 = new Date();
console.log(d0.formatDate("mmddyyyy"));
console.log(d0.formatDate("yyyymmdd"));
console.log(d0.formatDate("mmdd"));
Upvotes: 1