473,698 Members | 2,246 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 #1
27 1761
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.ge tMonth()-1)
alert( D.getDate()+'/'+(+D.getMonth( )+1)+'/'+D.getFullYear () );

--19/8/2008

--
sm
Sep 19 '08 #2
On Sep 19, 3:04*pm, SAM <stephanemoriau x.NoAd...@wanad oo.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.ge tMonth()-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
rhaazy <rh****@gmail.c omwrites:
On Sep 19, 3:04Â*pm, SAM <stephanemoriau x.NoAd...@wanad oo.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
rhaazy wrote:
On Sep 19, 3:04 pm, SAM <stephanemoriau x.NoAd...@wanad oo.fr.invalid>
wrote:
>var D = new Date();
D.setMonth(D.g etMonth()-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
rhaazy <rh****@gmail.c omwrites:
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(da te.getDate()-30);
var day = date.getDate();
var mth = date.getMonth() ;
var yr = date.getFullYea r();
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/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Sep 19 '08 #6
SAM
rhaazy a écrit :
On Sep 19, 3:04 pm, SAM <stephanemoriau x.NoAd...@wanad oo.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.g etMonth()-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.get Date()-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
SAM
Lasse Reichstein Nielsen a écrit :
rhaazy <rh****@gmail.c omwrites:
>>
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(da te.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.getFullYea r();
var format = (day < 10 ? "0" : "") + day + "/" +
(mth < 10 ? "0" : "") + mth + "/" +
yr;
Sep 19 '08 #8
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.flo or( /* this should be one line */
this.getFullYea r() / 100)).padFront( "0", 2);
} else if (nxt == "d") { // day of month (01 to 31)
buffer += String(this.get Date()).padFron t("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.get Hours()).padFro nt("0", 2);
} else if (nxt == "M") { // minutes (00 - 59)
buffer += String(this.get Minutes()).padF ront("0", 2);
} else if (nxt == "m") { // month of year (01 to 12)
buffer += String(this.get Month() + 1).padFront("0" , 2);
} else if (nxt == "n") { // newline
buffer += "\n";
} else if (nxt == "R") { // 24h time (%H:%M)
buffer += String(this.get Hours()).padFro nt("0", 2)
+ ":"
+ String(this.get Minutes()).padF ront("0", 2);
} else if (nxt == "S") { // seconds (00 - 59)
buffer += String(this.get Seconds()).padF ront("0", 2);
} else if (nxt == "T") { // 24h time (%H:%M:%S)
buffer += String(this.get Hours()).padFro nt("0", 2)
+ ":"
+ String(this.get Minutes()).padF ront("0", 2)
+ ":"
+ String(this.get Seconds()).padF ront("0", 2);
} else if (nxt == "Y") { // 4-digit year
buffer += this.getFullYea r();
} else if (nxt == "y") { // 2-digit year
var y = String(this.get FullYear());
buffer += y.substr(y.leng th -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.prototyp e.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.prototyp e.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
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.flo or( * /* this shouldbe one line */
* * * * * * * * this.getFullYea r() / 100)).padFront( "0", 2);
* * * * } else if (nxt == "d") { * *// day of month (01 to 31)
* * * * * * buffer += String(this.get Date()).padFron t("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.get Hours()).padFro nt("0",2);
* * * * } else if (nxt == "M") { * *// minutes (00 - 59)
* * * * * * buffer += String(this.get Minutes()).padF ront("0", 2);
* * * * } else if (nxt == "m") { * *// month of year (01 to 12)
* * * * * * buffer += String(this.get Month() + 1).padFront("0" , 2);
* * * * } else if (nxt == "n") { * *// newline
* * * * * * buffer += "\n";
* * * * } else if (nxt == "R") { * *// 24h time (%H:%M)
* * * * * * buffer += String(this.get Hours()).padFro nt("0",2)
* * * * * * * * * * + ":"
* * * * * * * * * * + String(this.get Minutes()).padF ront("0", 2);
* * * * } else if (nxt == "S") { * *// seconds (00 - 59)
* * * * * * buffer += String(this.get Seconds()).padF ront("0", 2);
* * * * } else if (nxt == "T") { * *// 24h time (%H:%M:%S)
* * * * * * buffer += String(this.get Hours()).padFro nt("0",2)
* * * * * * * * * * + ":"
* * * * * * * * * * + String(this.get Minutes()).padF ront("0", 2)
* * * * * * * * * * + ":"
* * * * * * * * * * + String(this.get Seconds()).padF ront("0", 2);
* * * * } else if (nxt == "Y") { * *// 4-digit year
* * * * * * buffer += this.getFullYea r();
* * * * } else if (nxt == "y") { * *// 2-digit year
* * * * * * var y = String(this.get FullYear());
* * * * * * buffer += y.substr(y.leng th -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.prototyp e.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.prototyp e.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

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

Similar topics

11
2851
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
8674
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
8603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9157
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8861
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
7725
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...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3046
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
2
2329
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.