Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Javascript and working with dates

Reply
Thread Tools

Javascript and working with dates

 
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      09-20-2008
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
 
Reply With Quote
 
 
 
 
Dr J R Stockton
Guest
Posts: n/a
 
      09-20-2008
On Sep 19, 4:12*pm, rhaazy <(E-Mail Removed)> wrote:
> 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, ...
 
Reply With Quote
 
 
 
 
Lasse Reichstein Nielsen
Guest
Posts: n/a
 
      09-20-2008
SAM <(E-Mail Removed)> writes:

> 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.'
 
Reply With Quote
 
sasuke
Guest
Posts: n/a
 
      09-20-2008
On Sep 20, 4:03*pm, Thomas 'PointedEars' Lahn <(E-Mail Removed)>
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 <(E-Mail Removed)> wrote:
> 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
 
Reply With Quote
 
Dr_KralNOSPAM@nyc.rr.com
Guest
Posts: n/a
 
      09-21-2008
On Fri, 19 Sep 2008 08:12:50 -0700 (PDT), rhaazy <(E-Mail Removed)> wrote
in <(E-Mail Removed)>:

>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.
 
Reply With Quote
 
Dr_KralNOSPAM@nyc.rr.com
Guest
Posts: n/a
 
      09-21-2008
On Sun, 21 Sep 2008 01:42:43 GMT, http://www.velocityreviews.com/forums/(E-Mail Removed) wrote in
<(E-Mail Removed)>:

>On Fri, 19 Sep 2008 08:12:50 -0700 (PDT), rhaazy <(E-Mail Removed)> wrote
>in <(E-Mail Removed)>:
>
>>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.

 
Reply With Quote
 
Lasse Reichstein Nielsen
Guest
Posts: n/a
 
      09-21-2008
(E-Mail Removed) 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.'
 
Reply With Quote
 
Dr_KralNOSPAM@nyc.rr.com
Guest
Posts: n/a
 
      09-21-2008
On Sun, 21 Sep 2008 04:02:36 +0200, Lasse Reichstein Nielsen
<(E-Mail Removed)> wrote in <(E-Mail Removed)>:

>(E-Mail Removed) 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.


 
Reply With Quote
 
Dr_KralNOSPAM@nyc.rr.com
Guest
Posts: n/a
 
      09-21-2008
please ignore this post -- shifting the date does work

sorry
 
Reply With Quote
 
rhaazy
Guest
Posts: n/a
 
      09-22-2008
On Sep 20, 11:25*pm, (E-Mail Removed) 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.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
RFC-822 dates into Ruby dates kellygreer1 Ruby 1 06-08-2008 10:59 PM
Need to use dates earlier than 1900 (Time library says out of range for dates < 1900) me@benjaminarai.com Ruby 1 07-17-2007 02:25 PM
FAQ Dates; Opera Dates. Dr J R Stockton Javascript 0 06-18-2007 03:51 PM
Dates dates dates dates... SQL and ASP.NET David Lozzi ASP .Net 1 09-30-2005 02:18 PM
Dates! Dates! Dates! PW ASP General 4 08-09-2004 04:42 PM



Advertisments