473,725 Members | 2,212 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Javascript and working with dates

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
27 1765
On Sun, 21 Sep 2008 04:02:36 +0200, Lasse Reichstein Nielsen
<lr********@gma il.comwrote in <r6**********@g mail.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(pa st.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
please ignore this post -- shifting the date does work

sorry
Sep 21 '08 #22
On Sep 20, 11:25*pm, Dr_KralNOS...@n yc.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
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 RegularExpressi onBody and
RegularExpressi onFlags
| 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
| RegularExpressi onLiteral. 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
[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 RegularExpressi onBody and
| RegularExpressi onFlags 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
| RegularExpressi onLiteral. 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
On Sep 22, 7:15*pm, "Thomas 'PointedEars' Lahn" <PointedE...@we b.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
In comp.lang.javas cript message <48************ *********@news. orange.fr>
, Sat, 20 Sep 2008 00:34:29, SAM <st************ *********@wanad oo.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.ge tDate()-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.demo n.co.uk/- FAQish topics, acronyms, & links.

Usenet News services are currently unreliable; I may not see all articles here.
Oct 9 '08 #27
In comp.lang.javas cript message <gb************ *@news.t-online.com>,
Fri, 19 Sep 2008 23:44:11, Stevo <no@mail.invali dposted:
>rhaazy wrote:
>On Sep 19, 3:04 pm, SAM <stephanemoriau x.NoAd...@wanad oo.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.demo n.co.uk/- FAQish topics, acronyms, & links.

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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
2854
by: Peter Pfeiffer | last post by:
I've written several scripts that have "while" blocks which increment a date by one day if the date does not match one of a group of dates. However, sometimes it apparently steps out out the while loop even though my condition isn't met. Will work for a few loops then steps out often. Are there javascript "date" issues? I have also noticed different results between Firefox and Internet Explorer. thanks for any comments,
5
2580
by: settyv | last post by:
Hi, Below is the Javascript function that am trying to call from asp:Button control. <script language="javascript"> function ValidateDate(fromDate,toDate) { var fromDate=new Date();
0
8888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9113
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8097
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3221
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.