By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,460 Members | 1,154 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,460 IT Pros & Developers. It's quick & easy.

Javascript and working with dates

P: n/a
I need to write some javascript that will return a date string in the
form mm/dd/yyyy.

The date needs to be today's date - 30 days.

Is there a relatively straight forward way to do this?

So far all I can find is a mess of variables for month, day, and year,
and combining some date functions together, etc etc. Seems like a lot
of work for what should be very simple.
Sep 19 '08 #1
Share this Question
Share on Google+
27 Replies


P: n/a
SAM
rhaazy a écrit :
I need to write some javascript that will return a date string in the
form mm/dd/yyyy.

The date needs to be today's date - 30 days.

Is there a relatively straight forward way to do this?
http://www.merlyn.demon.co.uk/js-date1.htm#incr
So far all I can find is a mess of variables for month, day, and year,
and combining some date functions together, etc etc. Seems like a lot
of work for what should be very simple.

and what do you think we have to do when we want the date in french ?
dd/mm/yyyy

var D = new Date();
D.setMonth(D.getMonth()-1)
alert( D.getDate()+'/'+(+D.getMonth()+1)+'/'+D.getFullYear() );

--19/8/2008

--
sm
Sep 19 '08 #2

P: n/a
On Sep 19, 3:04*pm, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
wrote:
rhaazy a écrit :
I need to write some javascript that will return a date string in the
form mm/dd/yyyy.
The date needs to be today's date - 30 days.
Is there a relatively straight forward way to do this?

http://www.merlyn.demon.co.uk/js-date1.htm#incr
So far all I can find is a mess of variables for month, day, and year,
and combining some date functions together, etc etc. *Seems like a lot
of work for what should be very simple.

and what do you think we have to do when we want the date in french ?
* dd/mm/yyyy

var D = new Date();
D.setMonth(D.getMonth()-1)
alert( D.getDate()+'/'+(+D.getMonth()+1)+'/'+D.getFullYear() );

* --19/8/2008

--
sm
Thats fine if all I want is a date, but to be able to subtract 30 days
from any given date introduces a huge mess of logic that needs to be
coded.
I decided to just find an open source date library that had decent
parsing functions for my purpose.

Thanks for the post.
Sep 19 '08 #3

P: n/a
rhaazy <rh****@gmail.comwrites:
On Sep 19, 3:04Â*pm, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
wrote:
Thats fine if all I want is a date, but to be able to subtract 30 days
from any given date introduces a huge mess of logic that needs to be
coded.
That's because dates - and times - are VERY messy. A library able to
manipulate dates that is complete enough to be /globally/ useful would
be very large. See for example the amount of stuff in the perl DateTime
project:

http://datetime.perl.org/?Modules
I decided to just find an open source date library that had decent
parsing functions for my purpose.
If you can find a decent library, that's probably the best way to handle
this problem.
--
Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/
Sep 19 '08 #4

P: n/a
rhaazy wrote:
On Sep 19, 3:04 pm, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
wrote:
>var D = new Date();
D.setMonth(D.getMonth()-1)
alert( D.getDate()+'/'+(+D.getMonth()+1)+'/'+D.getFullYear() );
--19/8/2008
Thats fine if all I want is a date, but to be able to subtract 30 days
from any given date introduces a huge mess of logic that needs to be
coded.
I can't recall any language that makes dealing with dates easy.
Sep 19 '08 #5

P: n/a
rhaazy <rh****@gmail.comwrites:
I need to write some javascript that will return a date string in the
form mm/dd/yyyy.

The date needs to be today's date - 30 days.

Is there a relatively straight forward way to do this?
var date = new Date();
date.setDate(date.getDate()-30);
var day = date.getDate();
var mth = date.getMonth();
var yr = date.getFullYear();
var format = (day < 10 ? "0" : "") + day + "/" +
(mth < 10 ? "0" : "") + mth + "/" +
yr;
So far all I can find is a mess of variables for month, day, and year,
and combining some date functions together, etc etc. Seems like a lot
of work for what should be very simple.
There isn't a date formatter built in. For most cases, it's not worth
it anyway. Just make one function to format your dates as you want
it and use that wherever it's needed.

/L
--
Lasse Reichstein Nielsen
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Sep 19 '08 #6

P: n/a
SAM
rhaazy a écrit :
On Sep 19, 3:04 pm, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
wrote:
>rhaazy a écrit :
>>I need to write some javascript that will return a date string in the
form mm/dd/yyyy.
The date needs to be today's date - 30 days.

var D = new Date();
D.setMonth(D.getMonth()-1)
alert( D.getDate()+'/'+(+D.getMonth()+1)+'/'+D.getFullYear() );

--19/8/2008

Thats fine if all I want is a date,
don't you want date ? ("mm/dd/yyyy" you did say)
but to be able to subtract 30 days
and *absoloutly* 30 days ?
from any given date introduces a huge mess of logic that needs to be
coded.
Example with a trap over February:
==================================
var y = 2005, m = 03, d = 30; // 30/03/2005 (in dd/mm/yyyy)
var D = new Date(y, +m-1, d); // the orginal JS date
D.setDate(D.getDate()-30); // 30 days less
// that is done
alert( d+'/'+m+'/'+y+
' = original date\n'+
D.getDate()+'/'+(+D.getMonth()+1)+'/'+D.getFullYear()+
' = date - 30 days'):
--
sm
Sep 19 '08 #7

P: n/a
SAM
Lasse Reichstein Nielsen a écrit :
rhaazy <rh****@gmail.comwrites:
>>
The date needs to be today's date - 30 days.

Is there a relatively straight forward way to do this?

var date = new Date();
date.setDate(date.getDate()-30);
var day = date.getDate();
var mth = date.getMonth();
months begin by '0' in JS. No ?
so :
var mth = +date.getMonth()+1;
var yr = date.getFullYear();
var format = (day < 10 ? "0" : "") + day + "/" +
(mth < 10 ? "0" : "") + mth + "/" +
yr;
Sep 19 '08 #8

P: n/a
On 2008-09-20 00:30, Lasse Reichstein Nielsen wrote:
There isn't a date formatter built in. For most cases, it's not worth
it anyway. Just make one function to format your dates as you want
it and use that wherever it's needed.
Here's one simple way to retro-fit a date formatting method. It
implements a subset of formats from strftime(3); the PHP function of the
same name is also similar. Some of the formats are missing, like the
names of months, week days, etc, because they were not required when the
method was written. Note: some of the formats are different from what
you might expect - read the comments and adjust the code as you see fit.
Usage:
var d = new Date(2008, 3, 4);
var dstr1 = d.fmt("%m/%d/%Y");
var dstr2 = d.fmt("%d.%m.%Y");
/* a simple date formatting method */
Date.prototype.fmt = function (format) {
var buffer = "";
var chr, nxt;
for (var i = 0, len = format.length; i < len; ++i) {
chr = format.substr(i, 1);
if (chr != "%") {
buffer += chr;
continue;
}
nxt = format.substr(i + 1, 1);
if (nxt == "C") { // 2-digit century (eg "19" or "20")
buffer += String(Math.floor( /* this should be one line */
this.getFullYear() / 100)).padFront("0", 2);
} else if (nxt == "d") { // day of month (01 to 31)
buffer += String(this.getDate()).padFront("0", 2);
} else if (nxt == "F") { // month of year (1 to 12)
buffer += (this.getMonth() + 1);
} else if (nxt == "f") { // day of month (1 to 31)
buffer += this.getDate();
} else if (nxt == "H") { // 24h hours (00 - 23)
buffer += String(this.getHours()).padFront("0", 2);
} else if (nxt == "M") { // minutes (00 - 59)
buffer += String(this.getMinutes()).padFront("0", 2);
} else if (nxt == "m") { // month of year (01 to 12)
buffer += String(this.getMonth() + 1).padFront("0", 2);
} else if (nxt == "n") { // newline
buffer += "\n";
} else if (nxt == "R") { // 24h time (%H:%M)
buffer += String(this.getHours()).padFront("0", 2)
+ ":"
+ String(this.getMinutes()).padFront("0", 2);
} else if (nxt == "S") { // seconds (00 - 59)
buffer += String(this.getSeconds()).padFront("0", 2);
} else if (nxt == "T") { // 24h time (%H:%M:%S)
buffer += String(this.getHours()).padFront("0", 2)
+ ":"
+ String(this.getMinutes()).padFront("0", 2)
+ ":"
+ String(this.getSeconds()).padFront("0", 2);
} else if (nxt == "Y") { // 4-digit year
buffer += this.getFullYear();
} else if (nxt == "y") { // 2-digit year
var y = String(this.getFullYear());
buffer += y.substr(y.length -2, 2);
} else if (nxt == "%") { // literal "%" character
buffer += "%";
} else {
buffer += format.substr(i, 2);
}
++i; // skip next
}
return buffer;
}
In this form, it also requires an extension to the String prototype object:

/* left-pads the string with {chr} until it is {len} characters long */
String.prototype.padFront = function (chr, len) {
if (this.length >= len) {
return this;
} else {
return chr.repeat(len - this.length) + this;
}
}

/* returns the string repeated {n} times */
String.prototype.repeat = function (n) {
if (n < 1) return "";
return (new Array(n + 1)).join(this);
}
If you don't like to mess with the native String and Date types, you
could refactor these methods as simple global methods (with date and
string arguments, respectively).
- Conrad
Sep 20 '08 #9

P: n/a
On Sep 20, 6:24*am, Conrad Lender <crlen...@yahoo.comwrote:
Usage:
* * var d = new Date(2008, 3, 4);
* * var dstr1 = d.fmt("%m/%d/%Y");
* * var dstr2 = d.fmt("%d.%m.%Y");

/* a simple date formatting method */
Date.prototype.fmt = function (format) {
* * var buffer = "";
* * var chr, nxt;
* * for (var i = 0, len = format.length; i < len; ++i) {
* * * * chr = format.substr(i, 1);
* * * * if (chr != "%") {
* * * * * * buffer += chr;
* * * * * * continue;
* * * * }
* * * * nxt = format.substr(i + 1, 1);
* * * * if (nxt == "C") { * * * * * // 2-digit century (eg "19" or "20")
* * * * * * buffer += String(Math.floor( * /* this shouldbe one line */
* * * * * * * * this.getFullYear() / 100)).padFront("0", 2);
* * * * } else if (nxt == "d") { * *// day of month (01 to 31)
* * * * * * buffer += String(this.getDate()).padFront("0", 2);
* * * * } else if (nxt == "F") { * *// month of year (1 to 12)
* * * * * * buffer += (this.getMonth() + 1);
* * * * } else if (nxt == "f") { * *// day of month (1 to31)
* * * * * * buffer += this.getDate();
* * * * } else if (nxt == "H") { * *// 24h hours (00 - 23)
* * * * * * buffer += String(this.getHours()).padFront("0",2);
* * * * } else if (nxt == "M") { * *// minutes (00 - 59)
* * * * * * buffer += String(this.getMinutes()).padFront("0", 2);
* * * * } else if (nxt == "m") { * *// month of year (01 to 12)
* * * * * * buffer += String(this.getMonth() + 1).padFront("0", 2);
* * * * } else if (nxt == "n") { * *// newline
* * * * * * buffer += "\n";
* * * * } else if (nxt == "R") { * *// 24h time (%H:%M)
* * * * * * buffer += String(this.getHours()).padFront("0",2)
* * * * * * * * * * + ":"
* * * * * * * * * * + String(this.getMinutes()).padFront("0", 2);
* * * * } else if (nxt == "S") { * *// seconds (00 - 59)
* * * * * * buffer += String(this.getSeconds()).padFront("0", 2);
* * * * } else if (nxt == "T") { * *// 24h time (%H:%M:%S)
* * * * * * buffer += String(this.getHours()).padFront("0",2)
* * * * * * * * * * + ":"
* * * * * * * * * * + String(this.getMinutes()).padFront("0", 2)
* * * * * * * * * * + ":"
* * * * * * * * * * + String(this.getSeconds()).padFront("0", 2);
* * * * } else if (nxt == "Y") { * *// 4-digit year
* * * * * * buffer += this.getFullYear();
* * * * } else if (nxt == "y") { * *// 2-digit year
* * * * * * var y = String(this.getFullYear());
* * * * * * buffer += y.substr(y.length -2, 2);
* * * * } else if (nxt == "%") { * *// literal "%" character
* * * * * * buffer += "%";
* * * * } else {
* * * * * * buffer += format.substr(i, 2);
* * * * }
* * * * ++i; // skip next
* * }
* * return buffer;

}

In this form, it also requires an extension to the String prototype object:

/* left-pads the string with {chr} until it is {len} characters long */
String.prototype.padFront = function (chr, len) {
* * if (this.length >= len) {
* * * * return this;
* * } else {
* * * * return chr.repeat(len - this.length) + this;
* * }

}

/* returns the string repeated {n} times */
String.prototype.repeat = function (n) {
* * if (n < 1) return "";
* * return (new Array(n + 1)).join(this);

}
Nice and compact implementation, 5 stars! A improvement here might be
using Array as buffer instead of String since Strings in Javascript
are immutable thereby preventing temporary string object creation.

/sasuke
Sep 20 '08 #10

P: n/a
sasuke wrote:
On Sep 20, 6:24 am, Conrad Lender <crlen...@yahoo.comwrote:
>Usage:
var d = new Date(2008, 3, 4);
var dstr1 = d.fmt("%m/%d/%Y");
var dstr2 = d.fmt("%d.%m.%Y");

/* a simple date formatting method */
Date.prototype.fmt = function (format) {
[50 lines of code]
}

In this form, it also requires an extension to the String prototype object:

/* left-pads the string with {chr} until it is {len} characters long */
String.prototype.padFront = function (chr, len) {
if (this.length >= len) {
return this;
} else {
return chr.repeat(len - this.length) + this;
}

}

/* returns the string repeated {n} times */
String.prototype.repeat = function (n) {
if (n < 1) return "";
return (new Array(n + 1)).join(this);

}

Nice and compact implementation, 5 stars!
Compact? Maybe String.prototype.padFront() and String.prototype.repeat().
A improvement here might be using Array as buffer instead of String
Or no user-defined buffer at all.
since Strings in Javascript are immutable thereby preventing temporary
string object creation.
Non sequitur.
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f8*******************@news.demon.co.uk>
Sep 20 '08 #11

P: n/a
Conrad Lender wrote:
On 2008-09-20 00:30, Lasse Reichstein Nielsen wrote:
>There isn't a date formatter built in. For most cases, it's not worth
it anyway. Just make one function to format your dates as you want
it and use that wherever it's needed.

Here's one simple way to retro-fit a date formatting method. It
implements a subset of formats from strftime(3); the PHP function of the
same name is also similar. Some of the formats are missing, like the
names of months, week days, etc, because they were not required when the
method was written. Note: some of the formats are different from what
you might expect - read the comments and adjust the code as you see fit.
[x] done
Usage:
var d = new Date(2008, 3, 4);
var dstr1 = d.fmt("%m/%d/%Y");
var dstr2 = d.fmt("%d.%m.%Y");
/* a simple date formatting method */
Date.prototype.fmt = function (format) {
var buffer = "";
var chr, nxt;
for (var i = 0, len = format.length; i < len; ++i) {
chr = format.substr(i, 1);
if (chr != "%") {
buffer += chr;
continue;
}
nxt = format.substr(i + 1, 1);
if (nxt == "C") { // 2-digit century (eg "19" or "20")
buffer += String(Math.floor( /* this should be one line */
this.getFullYear() / 100)).padFront("0", 2);
} else if (nxt == "d") { // day of month (01 to 31)
buffer += String(this.getDate()).padFront("0", 2);
} else if (nxt == "F") { // month of year (1 to 12)
buffer += (this.getMonth() + 1);
} else if (nxt == "f") { // day of month (1 to 31)
buffer += this.getDate();
} else if (nxt == "H") { // 24h hours (00 - 23)
buffer += String(this.getHours()).padFront("0", 2);
} else if (nxt == "M") { // minutes (00 - 59)
buffer += String(this.getMinutes()).padFront("0", 2);
} else if (nxt == "m") { // month of year (01 to 12)
buffer += String(this.getMonth() + 1).padFront("0", 2);
} else if (nxt == "n") { // newline
buffer += "\n";
} else if (nxt == "R") { // 24h time (%H:%M)
buffer += String(this.getHours()).padFront("0", 2)
+ ":"
+ String(this.getMinutes()).padFront("0", 2);
} else if (nxt == "S") { // seconds (00 - 59)
buffer += String(this.getSeconds()).padFront("0", 2);
} else if (nxt == "T") { // 24h time (%H:%M:%S)
buffer += String(this.getHours()).padFront("0", 2)
+ ":"
+ String(this.getMinutes()).padFront("0", 2)
+ ":"
+ String(this.getSeconds()).padFront("0", 2);
} else if (nxt == "Y") { // 4-digit year
buffer += this.getFullYear();
} else if (nxt == "y") { // 2-digit year
var y = String(this.getFullYear());
buffer += y.substr(y.length -2, 2);
} else if (nxt == "%") { // literal "%" character
buffer += "%";
} else {
buffer += format.substr(i, 2);
}
++i; // skip next
}
return buffer;
}
Date.prototype.fmt = function(format) {
var d = this;
return format.replace(/%([CdFfHMmnRSTYy%])/g,
function(m, p1) {
switch (p1)
{
case "C": return String(Math.floor(d.getFullYear() / 100))
.padFront("0", 2);
case "d": return String(d.getDate()).padFront("0", 2);
case "F": return d.getMonth() + 1;
case "f": return d.getDate();
case "H": return String(d.getHours()).padFront("0", 2);
case "M": return String(d.getMinutes()).padFront("0", 2);
case "m": return String(d.getMonth() + 1).padFront("0", 2);
case "n": return "\n";
case "R": return String(d.getHours()).padFront("0", 2)
+ ":"
+ String(d.getMinutes()).padFront("0", 2);
case "S": return String(d.getSeconds()).padFront("0", 2);
case "T": return String(d.getHours()).padFront("0", 2)
+ ":"
+ String(d.getMinutes()).padFront("0", 2)
+ ":"
+ String(d.getSeconds()).padFront("0", 2);
case "Y": return d.getFullYear();
case "y": return String(d.getFullYear() % 100).padFront("0", 2);
default: return p1;
}
});
};
PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
Sep 20 '08 #12

P: n/a
On Sep 19, 4:12*pm, rhaazy <rha...@gmail.comwrote:
I need to write some javascript that will return a date string in the
form mm/dd/yyyy.
Deprecanda est FFF.
The date needs to be today's date - 30 days.
Be aware that the user's date may differ from your date.
Is there a relatively straight forward way to do this?
D = new Date() ; D.setDate(D.getDate()-30)
with (D) X = String(101000000 + getMonth()*1e6 + getDate()*1e4 +
getFullYear())
.replace(/(.)(\d\d)(\d\d)/, "$2/$3/")
with (D) X = String(100 + getFullYear()*1e4 + getMonth()*1e2 +
getDate())
.replace(/(\d{4})(\d\d)(\d\d)/, "$2/$3/$1")

Only one of the with statements is required. This gives 2 2 4 digit
fields, unlike some.

--
(c) John Stockton, near London, UK. Posting with Google.
Mail: J.R.""""""""@physics.org or (better) via Home Page at
Web: <URL:http://www.merlyn.demon.co.uk/>
FAQish topics, acronyms, links, etc.; Date, Delphi, JavaScript, ...
Sep 20 '08 #13

P: n/a
On 2008-09-20 13:03, Thomas 'PointedEars' Lahn wrote:
Date.prototype.fmt = function(format) {
var d = this;
return format.replace(/%([CdFfHMmnRSTYy%])/g,
function(m, p1) {
switch (p1)
{
case "C": return String(Math.floor(d.getFullYear() / 100))
.padFront("0", 2);
case "d": return String(d.getDate()).padFront("0", 2);
case "F": return d.getMonth() + 1;
case "f": return d.getDate();
case "H": return String(d.getHours()).padFront("0", 2);
case "M": return String(d.getMinutes()).padFront("0", 2);
case "m": return String(d.getMonth() + 1).padFront("0", 2);
case "n": return "\n";
case "R": return String(d.getHours()).padFront("0", 2)
+ ":"
+ String(d.getMinutes()).padFront("0", 2);
case "S": return String(d.getSeconds()).padFront("0", 2);
case "T": return String(d.getHours()).padFront("0", 2)
+ ":"
+ String(d.getMinutes()).padFront("0", 2)
+ ":"
+ String(d.getSeconds()).padFront("0", 2);
case "Y": return d.getFullYear();
case "y": return String(d.getFullYear() % 100).padFront("0", 2);
default: return p1;
}
});
};
Nice touch, thanks.

Performance is comparable, by the way: about the same in Opera and
Firefox2; the string buffer method is about 30% faster in Firefox3, and
the regex method is about 20% faster in IE7. Outside of benchmarks, the
performance difference is negligible, of course. I think I like your
approach better, it's more compact and easier to maintain.
- Conrad
Sep 20 '08 #14

P: n/a
On 2008-09-20 09:43, sasuke wrote:
A improvement here might be using Array as buffer instead of String
That would be implementation dependant. After a quick check it looks
like an array buffer is actually a little slower in the browsers that
I've tested. IIRC, the speed difference between string concatenation and
array joins only favors the array if the substrings are rather long.
- Conrad
Sep 20 '08 #15

P: n/a
SAM <st*********************@wanadoo.fr.invalidwrite s:
months begin by '0' in JS. No ?
so :
var mth = +date.getMonth()+1;
Ack, yes, my mistake.

/L
--
Lasse Reichstein Nielsen
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Sep 20 '08 #16

P: n/a
On Sep 20, 4:03*pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
Date.prototype.fmt = function(format) {
* var d = this;
* return format.replace(/%([CdFfHMmnRSTYy%])/g,
* * function(m, p1) {
* * * switch (p1)
* * * {
* * * * case "C": return String(Math.floor(d.getFullYear() / 100))
* * * * * * * * * * * * *.padFront("0", 2);
* * * * case "d": return String(d.getDate()).padFront("0", 2);
* * * * case "F": return d.getMonth() + 1;
* * * * case "f": return d.getDate();
* * * * case "H": return String(d.getHours()).padFront("0", 2);
* * * * case "M": return String(d.getMinutes()).padFront("0", 2);
* * * * case "m": return String(d.getMonth() + 1).padFront("0", 2);
* * * * case "n": return "\n";
* * * * case "R": return String(d.getHours()).padFront("0", 2)
* * * * * * * * * * * * *+ ":"
* * * * * * * * * * * * *+ String(d.getMinutes()).padFront("0", 2);
* * * * case "S": return String(d.getSeconds()).padFront("0", 2);
* * * * case "T": return String(d.getHours()).padFront("0", 2)
* * * * * * * * * * * * *+ ":"
* * * * * * * * * * * * *+ String(d.getMinutes()).padFront("0", 2)
* * * * * * * * * * * * *+ ":"
* * * * * * * * * * * * *+ String(d.getSeconds()).padFront("0", 2);
* * * * case "Y": return d.getFullYear();
* * * * case "y": return String(d.getFullYear() % 100).padFront("0", 2);
* * * * default: return p1;
* * * }
* * });
};
Very good modifications. But won't it be better if we use a cached
copy of the RegExp native object instead of creating a new one on each
invocation?

On Sep 20, 9:09 pm, Conrad Lender <crlen...@yahoo.comwrote:
On 2008-09-20 09:43, sasuke wrote:
A improvement here might be using Array as buffer instead of String

That would be implementation dependant. After a quick check it looks
like an array buffer is actually a little slower in the browsers that
I've tested. IIRC, the speed difference between string concatenation and
array joins only favors the array if the substrings are rather long.
I necessarily didn't mean performance in terms of speed, but more so
in terms of memory. Though there is no reliable way of tracking memory
allocation in browser embedded Javascript, I am pretty sure the Array
method ends up taking much less memory than the String concatenation
approach.

/sasuke
Sep 20 '08 #17

P: n/a
On Fri, 19 Sep 2008 08:12:50 -0700 (PDT), rhaazy <rh****@gmail.comwrote
in <c6**********************************@k36g2000pri. googlegroups.com>:
>I need to write some javascript that will return a date string in the
form mm/dd/yyyy.

The date needs to be today's date - 30 days.

Is there a relatively straight forward way to do this?
Yes!

Let JS do all the complex logic of various month lengths, leap years and
year boundaries.

var past = new Date(new Date().getTime() - 30*24*60*60000)
var mm=past.getMonth().valueOf()+1
if (mm<10) mm="0"+mm
var dd=past.getDate()
if(dd<10) dd="0"+dd
result=mm+"/"+dd+"/"+past.getFullYear()

I'm sure that there is a cleaner way to force two digit fields.

If m/d/yyyy is acceptable then:
var past = new Date(new Date().getTime() - 30*24*60*60000)
result=(past.getMonth().valueOf()+1)+"/"+dd=past.getDate()+"/"+past.getFullYear()

Can't get much simplier than two lines.

K.
Sep 21 '08 #18

P: n/a
On Sun, 21 Sep 2008 01:42:43 GMT, Dr***********@nyc.rr.com wrote in
<5l********************************@4ax.com>:
>On Fri, 19 Sep 2008 08:12:50 -0700 (PDT), rhaazy <rh****@gmail.comwrote
in <c6**********************************@k36g2000pri. googlegroups.com>:
>>I need to write some javascript that will return a date string in the
form mm/dd/yyyy.

The date needs to be today's date - 30 days.

Is there a relatively straight forward way to do this?

Yes!

Let JS do all the complex logic of various month lengths, leap years and
year boundaries.

var past = new Date(new Date().getTime() - 30*24*60*60000)
var mm=past.getMonth().valueOf()+1
if (mm<10) mm="0"+mm
var dd=past.getDate()
if(dd<10) dd="0"+dd
result=mm+"/"+dd+"/"+past.getFullYear()

I'm sure that there is a cleaner way to force two digit fields.

If m/d/yyyy is acceptable then:
var past = new Date(new Date().getTime() - 30*24*60*60000)
result=(past.getMonth().valueOf()+1)+"/"+dd=past.getDate()+"/"+past.getFullYear()
Oppps - typo above
result=(past.getMonth().valueOf()+1)+"/"+past.getDate()+"/"+past.getFullYear()
>
Can't get much simplier than two lines.

K.
Sep 21 '08 #19

P: n/a
Dr***********@nyc.rr.com writes:
Let JS do all the complex logic of various month lengths, leap years and
year boundaries.
Agree ...
var past = new Date(new Date().getTime() - 30*24*60*60000)
which is why this is not the way to do it. You are asking for a point
in time that is 30 * 24 hours earlier. That's not always the same as
30 days. Some days are 25 hours, some are 23, due to daylight saving
transition. This code will fail to give the correct day in some cases.

Use:
var past = new Date();
past.setDate(past.getDate()-30);
That gives the same time, 30 days earlier. Let Javascript do the
calculation for you.

/L
--
Lasse Reichstein Nielsen
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Sep 21 '08 #20

P: n/a
On Sun, 21 Sep 2008 04:02:36 +0200, Lasse Reichstein Nielsen
<lr********@gmail.comwrote in <r6**********@gmail.com>:
>Dr***********@nyc.rr.com writes:
>Let JS do all the complex logic of various month lengths, leap years and
year boundaries.

Agree ...
>var past = new Date(new Date().getTime() - 30*24*60*60000)

which is why this is not the way to do it. You are asking for a point
in time that is 30 * 24 hours earlier. That's not always the same as
30 days. Some days are 25 hours, some are 23, due to daylight saving
transition. This code will fail to give the correct day in some cases.
An interesting point. This error will occur if and only if one includes a
23 or 25 hour day AND is in a boundry period of the first or last hour of
the day. That can happen only two hours a year.

One can correct for this by shifting the current time to noon:
var past = new Date( new Date().setHours(12) - 30*24*60*60000 )

The OP did not indicate if the question was 30 24hour days or 30 calendar
days.

>Use:
var past = new Date();
past.setDate(past.getDate()-30);
That gives the same time, 30 days earlier.
NO!

That will work only if the previous month is 30 days (some are 28, 29, 31).
So it is correct only in three months - June, October and December. It
fails in most of May because in the USA DST happens in April.

BTW, if you start in January, then you will go forward some 11 months
unless you adjust the year also but even then the December day of month
will be one low.
Sep 21 '08 #21

P: n/a
please ignore this post -- shifting the date does work

sorry
Sep 21 '08 #22

P: n/a
On Sep 20, 11:25*pm, Dr_KralNOS...@nyc.rr.com wrote:
please ignore this post -- shifting the date does work

sorry
Thank you everyone for the discussion. This code is a lot cleaner
than what I had, and I learned a lot about the various date functions.
Sep 22 '08 #23

P: n/a
sasuke wrote:
Thomas 'PointedEars' Lahn wrote:
Date.prototype.fmt = function(format) {
var d = this;
return format.replace(/%([CdFfHMmnRSTYy%])/g,
function(m, p1) {
[...]
});
};

Very good modifications. But won't it be better if we use a cached
copy of the RegExp native object instead of creating a new one on each
invocation?
It would, if what you describe were the case. With a RegExp literal
no new object is created, but an already existing object is being
referred to. So there is no need for optimization through "caching":

,-[ECMAScript Language Specification, Edition 3 Final]
|
| 7 Lexical Conventions
|
| The source text of an ECMAScript program is first converted into
| a sequence of input elements, which are either tokens, line
terminators,
| comments, or white space. The source text is scanned from left to
right,
| repeatedly taking the longest possible sequence of characters as
| the next input element.
|
| [...]
|
| 7.8.5 Regular Expression Literals
|
| A regular expression literal is an input element that is converted
to
| a RegExp object (section 15.10) when it is scanned. The object is
| created before evaluation of the containing program or function
begins.
| Evaluation of the literal produces a reference to that object; it
does
| not create a new object.
|
| [...]
| Semantics
|
| A regular expression literal stands for a value of the Object type.
| This value is determined in two steps: first, the characters
comprising
| the regular expression's RegularExpressionBody and
RegularExpressionFlags
| production expansions are collected uninterpreted into two strings
Pattern
| and Flags, respectively. Then the new RegExp constructor is called
with
| two arguments Pattern and Flags and the result becomes the value of
the
| RegularExpressionLiteral. If the call to new RegExp generates an
error,
| an implementation may, at its discretion, either report the error
| immediately while scanning the program, or it may defer the error
until
| the regular expression literal is evaluated in the course of program
| execution.
PointedEars
Sep 22 '08 #24

P: n/a
[supersedes GG-miswrapped version]

sasuke wrote:
Thomas 'PointedEars' Lahn wrote:
Date.prototype.fmt = function(format) {
var d = this;
return format.replace(/%([CdFfHMmnRSTYy%])/g,
function(m, p1) {
[...]
});
};

Very good modifications.
Thanks.
But won't it be better if we use a cached copy of the RegExp
native object instead of creating a new one on each invocation?
It would, if what you describe were the case. With a RegExp literal
no new object is created, but an already existing object is being
referred to. So there is no need for optimization through "caching":

,-[ECMAScript Language Specification, Edition 3 Final]
|
| 7 Lexical Conventions
|
| The source text of an ECMAScript program is first converted into
| a sequence of input elements, which are either tokens, line
| terminators, comments, or white space. The source text is scanned
| from left to right, repeatedly taking the longest possible sequence
| of characters as the next input element.
|
| [...]
|
| 7.8.5 Regular Expression Literals
|
| A regular expression literal is an input element that is converted
| to a RegExp object (section 15.10) when it is scanned. The object
| is created before evaluation of the containing program or function
| begins. Evaluation of the literal produces a reference to that
| object; it does not create a new object.
|
| [...]
| Semantics
|
| A regular expression literal stands for a value of the Object type.
| This value is determined in two steps: first, the characters
| comprising the regular expression's RegularExpressionBody and
| RegularExpressionFlags production expansions are collected
| uninterpreted into two strings Pattern and Flags, respectively.
| Then the new RegExp constructor is called with two arguments
| Pattern and Flags and the result becomes the value of the
| RegularExpressionLiteral. If the call to new RegExp generates an
| error, an implementation may, at its discretion, either report
| the error immediately while scanning the program, or it may defer
| the error until the regular expression literal is evaluated in
| the course of program execution.
PointedEars
Sep 22 '08 #25

P: n/a
On Sep 22, 7:15*pm, "Thomas 'PointedEars' Lahn" <PointedE...@web.de>
wrote:
[supersedes GG-miswrapped version]

sasuke wrote:
Thomas 'PointedEars' Lahn wrote:
Date.prototype.fmt = function(format) {
* var d = this;
* return format.replace(/%([CdFfHMmnRSTYy%])/g,
* * function(m, p1) {
* * * [...]
* * });
};
Very good modifications.

Thanks.
You are most welcome.
But won't it be better if we use a cached copy of the RegExp
native object instead of creating a new one on each invocation?

It would, if what you describe were the case. *With a RegExp literal
no new object is created, but an already existing object is being
referred to. *So there is no need for optimization through "caching":

,-[ECMAScript Language Specification, Edition 3 Final]

[enlightening piece of text]
My bad; I did search the specification document for words like
'cache', 'cached' etc. in terms of Regular expressions but to no
avail. I should have known better than trying to use implementation
dependent terms as search keywords. I have always used global RegExp
literals for two reasons: to prevent new RegExp object creation and
for the sake of maintainability; I guess I need to strike out the
former.

It would be interesting to note the behavior of the implementation in
memory limited environment when faced with a extremely large number of
RegExp literals; would it then go in favor of implementing LFU/LRU
policy or prefer to throw an OOM (out of memory) error. Just a thought
though.

/sasuke
Sep 22 '08 #26

P: n/a
In comp.lang.javascript message <48*********************@news.orange.fr>
, Sat, 20 Sep 2008 00:34:29, SAM <st*********************@wanadoo.fr.inv
alidposted:
>
Example with a trap over February:
==================================
var y = 2005, m = 03, d = 30; // 30/03/2005 (in dd/mm/yyyy)
var D = new Date(y, +m-1, d); // the orginal JS date
D.setDate(D.getDate()-30); // 30 days less
// that is done
alert( d+'/'+m+'/'+y+
' = original date\n'+
D.getDate()+'/'+(+D.getMonth()+1)+'/'+D.getFullYear()+
' = date - 30 days'):

As new Date() is not used, then it is not a "real-time" question. For
such, it is more efficient, and in some cases may avoid obscure error,
to work entirely in UTC.

var D = new Date(Date.UTC(y, m-1, d - 30))
// then output D using UTC methods.

If there are still browsers that don't like non-positive day-of-month,
then move the 30 to between the parentheses, multiplying it by 864e5.

--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/- FAQish topics, acronyms, & links.

Usenet News services are currently unreliable; I may not see all articles here.
Oct 9 '08 #27

P: n/a
In comp.lang.javascript message <gb*************@news.t-online.com>,
Fri, 19 Sep 2008 23:44:11, Stevo <no@mail.invalidposted:
>rhaazy wrote:
>On Sep 19, 3:04 pm, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
wrote:
>>var D = new Date();
D.setMonth(D.getMonth()-1)
alert( D.getDate()+'/'+(+D.getMonth()+1)+'/'+D.getFullYear() );
--19/8/2008
Thats fine if all I want is a date, but to be able to subtract 30 days
from any given date introduces a huge mess of logic that needs to be
coded.

I can't recall any language that makes dealing with dates easy.
Icelandic Javascript. UTC all year round, unless they join the EU.
VBScript, for those few who are Americans or similar AND have discovered
DateSerial(y,m,d).

Opera is 9.60.

--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/- FAQish topics, acronyms, & links.

Usenet News services are currently unreliable; I may not see all articles here.
Oct 9 '08 #28

This discussion thread is closed

Replies have been disabled for this discussion.