469,623 Members | 1,800 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,623 developers. It's quick & easy.

date functions

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


Jul 23 '05 #1
15 3655
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>
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jul 23 '05 #2
Paul J. Ettl wrote:
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();
www.paul.ettl.at


This should be part of a signature, delimited with a line containing only
"-- " (dashDashSpace). Otherwise repeated posting of this could be
considered spam.
PointedEars
Jul 23 '05 #3
Thomas 'PointedEars' Lahn <Po*********@nurfuerspam.de> writes:
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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #4
JRS: In article <40**************@PointedEars.de>, seen in
news:comp.lang.javascript, Thomas 'PointedEars' Lahn
<Po*********@nurfuerspam.de> posted at Sun, 6 Jun 2004 23:46:52 :
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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #5
rh
Dr John Stockton wrote:

<snip>
function leadingZero(


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
Jul 23 '05 #6
JRS: In article <is**********@hotpop.com>, seen in
news:comp.lang.javascript, Lasse Reichstein Nielsen <lr*@hotpop.com>
posted at Mon, 7 Jun 2004 19:23:53 :
Thomas 'PointedEars' Lahn <Po*********@nurfuerspam.de> writes:
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.


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 ...

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #7
rh wrote:
Dr John Stockton wrote:
<snip>
>function leadingZero(


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;


Correct. The above line is equivalent to

s = s + "0" + s;

It should be

s = "0" + s;

of course.
PointedEars
Jul 23 '05 #8
rh
"Paul J. Ettl" <et**@ettl.at> wrote in message news:<c9***********@ulysses.news.tiscali.de>...
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
Jul 23 '05 #9
JRS: In article <29**************************@posting.google.com >, seen
in news:comp.lang.javascript, rh <co********@yahoo.ca> posted at Mon, 7
Jun 2004 21:14:12 :
"Paul J. Ettl" <et**@ettl.at> wrote in message news:<c9***********@ulysses.news.
tiscali.de>...
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);


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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #10
rh
Dr John Stockton wrote:

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).
// 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.


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.
// 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.


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
Jul 23 '05 #11
JRS: In article <29**************************@posting.google.com >, seen
in news:comp.lang.javascript, rh <co********@yahoo.ca> posted at Tue, 8
Jun 2004 15:46:07 :

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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #12
rh
Dr John Stockton <sp**@merlyn.demon.co.uk> wrote in message news:<Am**************@merlyn.demon.co.uk>...
JRS: In article <29**************************@posting.google.com >, seen
in news:comp.lang.javascript, rh <co********@yahoo.ca> posted at Tue, 8
Jun 2004 15:46:07 :

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.


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
Jul 23 '05 #13
JRS: In article <29**************************@posting.google.com >, seen
in news:comp.lang.javascript, rh <co********@yahoo.ca> posted at Wed, 9
Jun 2004 15:26:50 :
Dr John Stockton <sp**@merlyn.demon.co.uk> wrote in message news:<AmOc1VFXluxAFw
w+@merlyn.demon.co.uk>...
JRS: In article <29**************************@posting.google.com >, seen
in news:comp.lang.javascript, rh <co********@yahoo.ca> posted at Tue, 8
Jun 2004 15:46:07 :
>
>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.


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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #14
rh
Dr John Stockton wrote:

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


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.

<snip>
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
Jul 23 '05 #15
JRS: In article <29**************************@posting.google.com >, seen
in news:comp.lang.javascript, rh <co********@yahoo.ca> posted at Fri, 11
Jun 2004 08:51:44 :
Dr John Stockton wrote:

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


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.
<snip>
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.


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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #16

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by ndsoumah | last post: by
8 posts views Thread by Gerrit Holl | last post: by
4 posts views Thread by Ekong, Samuel Akpan | last post: by
12 posts views Thread by Assimalyst | last post: by
30 posts views Thread by fniles | last post: by
9 posts views Thread by Martin | last post: by
reply views Thread by devrayhaan | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.