Paul J. Ettl said:
Two questions:
I use
var date1 = new Date();
to get todays date. But how can I get yesterdays date?
Furthermore I use
var ydat = date1.getYear();
var mdat = date1.getMonth()+1;
var hdat = "0"+date1.getDate();
var ddat = hdat.substr(htag.length-2);
var datum=ydat+"-0"+mdat+"-"+ddat;
to get a string like 2004-06-01
Is there a easier way to format the date?
You were on the right track (I assume that the undefined "htag" was
something missed in translation).
You should be able to left pad with zeros to a width of 2 in basic
Javascript by:
var paddedStr = ("00"+num).substr(-2);
Unfortunately, while most recent browsers perform correctly, MS IE
fails to meet the current standard for the negative start index for
the substr method.
A variation on an earlier theme would be to create a general pad
function as a prototype. E.g.,
// Create the internal pad prototype
String.prototype._pad = function(width,padChar,side) {
var str = [side ? "" : this, side ? this : ""];
while (str[side].length < (width ? width : 0)
&& (str[side] = str[1] +(padChar ? padChar : " ")+str[0] ));
return str[side];
}
// Create pad functions for general use
// "width" is the total width to pad to,
// "padChar" is the optional pad character -- default " "
String.prototype.padLeft = function(width,padChar) {
return this._pad(width,padChar,0) };
String.prototype.padRight = function(width,padChar) {
return this._pad(width,padChar,1) };
Number.prototype.padLeft = function(width,padChar) {
return (""+this).padLeft(width,padChar) };
Number.prototype.padRight = function(width,padChar) {
return (""+this).padRight(width,padChar) };
// Date formatting:
// Add a getFullYear method if not supported (untested)
if (! Date.prototype.getFullYear) {
Date.prototype.getFullYear = function() {
return this.getYear() + 1900 }
}
// Create a formatting method for dates as a prototype
Date.prototype.dateFmt = function(d) {
d = d || this;
return d.getFullYear()+"-"+d.getMonth().padLeft(2,"0")
+"-"+d.getDate().padLeft(2,"0");
}
// Test
alert("Formatted date: "+ new Date().dateFmt() );
../rh