date functions

P

Paul J. Ettl

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?



Paul Ettl
www.paul.ettl.at
 
E

Evertjan.

Paul J. Ettl wrote on 01 jun 2004 in comp.lang.javascript:
to get todays date. But how can I get yesterdays date?

Forgetting summer time changes this gives you same time 1 day earlier:

var D = new Date()
D.setDate(D.getDate()-1)

alert(D)
Is there a easier way to format the date?


function LZ(x) { return (x<0||x>=10?"":"0") + x }
var D = new Date() ;
D = D.getFullYear()+'-'+LZ(D.getMonth()+1)+'-'+LZ(D.getDate())

alert(D)

all from John Stockton's pages:

<http://www.merlyn.demon.co.uk/js-dates.htm>
 
T

Thomas 'PointedEars' Lahn

Paul said:
I use

var date1 = new Date();

to get todays date. But how can I get yesterdays date?

var dYesterday = new Date(new Date().setDate(-1));

(Works at least in Mozilla/5.0 and IE 6.0 Win.)
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;
^^
You concatenate that always, so you could
end up with something like 2004-012-031.
to get a string like 2004-06-01

Is there a easier way to format the date?

Depends what you mean by that. There is certainly a *better* way:

// Helper method

function leadingZero(
/** @optional string */ s,
/** @optional number */ n)
/**
* @partof
* http://pointedears.de/scripts/string.js
* @param s
* Input string. If omitted and the calling object
* has a numeric <code>length</code> property, the
* result of its toString() method is used instead.
* @param n
* Length of the resulting string. The default is 1,
* i.e. if the input string is empty, "0" is returned.
* @returns the input string with leading zeros so that
* its length is @{(n)}</code>.
*/
{
if (this.length != "undefined"
&& !isNaN(this.length)
&& typeof s == "undefined")
{
s = this;
}

if (typeof s != "string")
{
s = s.toString();
}

while (s.length < n)
{
s += "0" + s;
}

return s;
}
String.prototype.leadingZero = leadingZero;

// Featured code

function date_ymd(d)
{
if (!(d instanceof Date))
{
if (this instanceof Date)
{
d = this;
}
else
{
d = new Date(d);
}
}

var y = d.getFullYear ? d.getFullYear() : d.getYear();
if (y < 1900)
{
y += 1900;
}

return (y
+ "-" + leadingZero(d.getMonth + 1, 2)
+ "-" + leadingZero(d.getDate(), 2));
}
Date.prototype.ymd = date_ymd;

var datum = new Date().ymd();

This should be part of a signature, delimited with a line containing only
"-- " (dashDashSpace). Otherwise repeated posting of this could be
considered spam.


PointedEars
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
Thomas 'PointedEars' Lahn
Paul J. Ettl wrote:
But how can I get yesterdays date?

var dYesterday = new Date(new Date().setDate(-1));

(Works at least in Mozilla/5.0 and IE 6.0 Win.)

I would expect that to give the last day of the previous month, in any
browser; it does so in MSIE4.

with (dY = new Date()) setDate(getDate()-1)

gives yesterday (at the present time thereof, if possible), and should
do so in any browser.

function leadingZero(

Seems to give wrong result in MSIE4.

For one who persistently wastes space in complaining about legitimate
attributions, you so seem to have rather a long-winded programming
style.

var y = d.getFullYear ? d.getFullYear() : d.getYear();
if (y < 1900)
{
y += 1900;
}


I see no point in attempting getFullYear if getYear is being coded for
satisfactorily.


This should be part of a signature, delimited with a line containing only
"-- " (dashDashSpace). Otherwise repeated posting of this could be
considered spam.

Ignore that; the child is deranged. As it stands, it is a legitimate
part of the body of the message. The proper meaning of the term "spam"
is Excessive Multiple Posting; thus the term would not apply in any
case.
 
L

Lasse Reichstein Nielsen

Thomas 'PointedEars' Lahn said:
Paul J. Ettl wrote:
var dYesterday = new Date(new Date().setDate(-1));

(Works at least in Mozilla/5.0 and IE 6.0 Win.)

Nope. It always becomes the next-to-last day of the previous month,
which can never be yesterday.

If you insist on doing it on one line, you can use
var yesterday = new Date(new Date().setDate(new Date().getDate()-1));
Or just do:
var yesterday = new Date();
yesterday.setDate(yesterday.getDate()-1);

/L
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
Nope. It always becomes the next-to-last day of the previous month,
which can never be yesterday.

Agreed. I'd forgotten May 31st.

If you insist on doing it on one line, you can use
var yesterday = new Date(new Date().setDate(new Date().getDate()-1));

That may be unsafe, if the month changes between the first and second
new Date(). Unless one needs to detect the passage of time, new Date()
should be called only once. Of course, it almost never matters.

Or just do:
var yesterday = new Date();
yesterday.setDate(yesterday.getDate()-1);

var yesterday = new Date() ; yesterday.setDate(yesterday.getDate()-1) ;
is on one line ...
 
R

rh

Dr John Stockton wrote:

Seems to give wrong result in MSIE4.

I expect it gives the wrong result everywhere because the following
line in it appears to be badly borken, causing the entire thing to
fork up:

s += "0" + s;

../rh
 
T

Thomas 'PointedEars' Lahn

rh said:
Dr John Stockton wrote:


I expect it gives the wrong result everywhere because the following
line in it appears to be badly borken, causing the entire thing to
fork up:

s += "0" + s;

Correct. The above line is equivalent to

s = s + "0" + s;

It should be

s = "0" + s;

of course.


PointedEars
 
R

rh

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
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen
in news:comp.lang.javascript said:
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);

Left padding to a length of two is so commonly wanted, in comparison
with padding to other lengths, that ISTM that it should be done with a
specific short-named function. I find a function grammatically more
convenient than a method.

The input is expected to be an integer in 0..99. Because programmers
and users are not infallible, ISTM that for input out of range a
function should EITHER give a clear error indication, OR give a string
properly representing the numeric value. For the latter case, I use

function LZ(x) { return (x<0||x>=10?"":"0") + x }


// Add a getFullYear method if not supported (untested)
if (! Date.prototype.getFullYear) {
Date.prototype.getFullYear = function() {
return this.getYear() + 1900 }
}

I have been informed :-

In older Javascript, getYear() returned the year minus 1900, YY only.
Later ones, for years after 1999, return the year, YYYY.
Before 1900 is worse; expect either of YYYY or YYYY-1900.

<p>"GetYear can return any one of these three sequences for years:
97,98,99,00,01 or 97,98,99,2000,2001 or 97,98,99,100,101".

Just adding 1900 seems unsafe. See below. Indeed, in my MSIE4, new
Date().getYear() gives 2004 and new Date(1888,8,8).getYear() gives
1888.

// 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");
}

IIRC, there is much to be said for adding 1 to the Month here.
 
R

rh

Dr said:
Left padding to a length of two is so commonly wanted, in comparison
with padding to other lengths, that ISTM that it should be done with a
specific short-named function. I find a function grammatically more
convenient than a method.

It may be just a matter of style. I don't really see it as any diffent
than any other padding.

Nonetheless, what's really wanted, I think, is a number formatting
capability that's based on string templates (even early FORTRAN had a
FORMAT statement, so the idea's not exactly new :)). Also, it's not
difficult to produce one in Javascript.
The input is expected to be an integer in 0..99. Because programmers
and users are not infallible, ISTM that for input out of range a
function should EITHER give a clear error indication, OR give a string
properly representing the numeric value. For the latter case, I use

function LZ(x) { return (x<0||x>=10?"":"0") + x }

Agreed, methods that provide a clear indication of success or failure
via return value are highly preferrable (and I debated about whether,
as a matter of good style, to add them in the sample methods
produced).
I have been informed :-

In older Javascript, getYear() returned the year minus 1900, YY only.
Later ones, for years after 1999, return the year, YYYY.
Before 1900 is worse; expect either of YYYY or YYYY-1900.

<p>"GetYear can return any one of these three sequences for years:
97,98,99,00,01 or 97,98,99,2000,2001 or 97,98,99,100,101".

Just adding 1900 seems unsafe. See below. Indeed, in my MSIE4, new
Date().getYear() gives 2004 and new Date(1888,8,8).getYear() gives
1888.

Which perhaps is sufficient to say attempting to emulate a bad idea is
a bad idea? Probably not that hard to improve though, if you can
reliably determine the expected range of the year.
IIRC, there is much to be said for adding 1 to the Month here.

Good recollection :).

Let's make the above

return d.getFullYear()+"-"+(d.getMonth()+1).padLeft(2,"0")
+"-"+d.getDate().padLeft(2,"0");

in consideration of the fact that getMonth returns a zero-based value.

../rh
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen
in news:comp.lang.javascript said:
Which perhaps is sufficient to say attempting to emulate a bad idea is
a bad idea? Probably not that hard to improve though, if you can
reliably determine the expected range of the year.

Indeed. But perhaps you have not examined what the newsgroup FAQ has to
say on dates.
 
R

rh

Dr John Stockton said:
JRS: In article <[email protected]>, seen


Indeed. But perhaps you have not examined what the newsgroup FAQ has to
say on dates.

From time to time, but I quite often suffer from "retention deficit
disorder". Thanks for the reminder.

From http://www.merlyn.demon.co.uk/js-date1.htm#TDY:

if (!Date.getFullYear) { // needs full test
Date.prototype.getFullYear =
new Function("return (X=this.getYear())>999 ? X : 1900+X") }

IIRC, there is much to be said for use of "prototype" as part of the
test.

../rh
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen
in news:comp.lang.javascript said:
From time to time, but I quite often suffer from "retention deficit
disorder". Thanks for the reminder.

From http://www.merlyn.demon.co.uk/js-date1.htm#TDY:

if (!Date.getFullYear) { // needs full test
Date.prototype.getFullYear =
new Function("return (X=this.getYear())>999 ? X : 1900+X") }

IIRC, there is much to be said for use of "prototype" as part of the
test.

That's actually in the previous section, #Y2k.

I now see that it will not always work, noting the earlier-quoted part
of my date2000.htm :

"GetYear can return any one of these three sequences for years:
97,98,99,00,01 or 97,98,99,2000,2001 or 97,98,99,100,101".

Where such a range can be defined, it seems best to take only the last
two digits of getYear() and to window them into a 100-year range -
possibly a sliding range.

That would do for a paediatric or geriatric unit; but not for a general
hospital.


Otherwise, we know that the answer must be close to YE in
YE = Math.round(getTime() / 864e5 / 365.2425) + 1970
but will, rarely, differ by a year; that may affect the first two
digits, so it's not possible to use 100*(YE div 100)+Y2 :
Y2 = getYear()%100
DY = (YE-Y2)%100 ; if (DY>50) DY -= 100 // DY = 0+-1 ?
FullYear = YE-DY

By using getYear, rather than only getTime, time zone is accommodated.

That needs further thought and testing before use. My js-date1,htm is
updated.
 
R

rh

Dr John Stockton wrote:


Too subtle, I see :). I believe you intended to use:

if (! Date.prototype.getFullYear)

in place of:

if (!Date.getFullYear)

in the test(s) for pre-existence. Otherwise, a browser supported
getFullYear will be overridden, which I would think to be neither the
intention nor desirable.

That needs further thought and testing before use. My js-date1,htm is
updated.

I'll defer to your expertise and further testing on the enhanced
version.

../rh
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen
in news:comp.lang.javascript said:
Dr John Stockton wrote:



Too subtle, I see :). I believe you intended to use:

if (! Date.prototype.getFullYear)

in place of:

if (!Date.getFullYear)

in the test(s) for pre-existence. Otherwise, a browser supported
getFullYear will be overridden, which I would think to be neither the
intention nor desirable.

Your "intended" is perhaps a bit strong - "ought to have intended",
maybe. It does come from a rather tentative bit of the Web page. Page
master now changed, thanks.
I'll defer to your expertise and further testing on the enhanced
version.

Updated again. This function seems likely to be OK, for >= AD 100 :-

function getFY(D) { var YE // needs full test in all browsers
YE = Math.round(D.getTime() / 31556952000) + 1970
return YE + (D.getYear()-YE)%100 }

Read it backwards; the result takes only the last 2 digits of getYear,
and is independent of the last two digits of YE; YE is about right, but
has misplaced Leap Years. The result of %100 is about mid-range; its
range is -99..+99. 31556952000 = 864e5 * 365.2425. The value of 1970
has a tolerance of over +-95; the divisor will also have a generous
tolerance.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,226
Latest member
KristanTal

Latest Threads

Top