473,320 Members | 1,883 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Incorrect date

I've adapted the following code so that it prints the date in
DD/MM/YYYY format. However it prints the incorrect date! If todays
date is 01/01/2003 it prints 03/01/2003 - 3 days out! What have I done
wrong?
<script language="Javascript">
aCalendar = new Date();
CalendarDay = aCalendar.getDay();
CalendarMonth = aCalendar.getMonth();
CalendarDate = aCalendar.getDate();
CalendarYear = aCalendar.getYear();

var monthname = new Array ("01", "02", "03", "04", "05", "06", "07",
"08", "09", "10", "11", "12" );
var dayname = new Array ("01", "02", "03", "04", "05", "06", "07",
"08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18",
"19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29",
"30", "31" );

if (CalendarDate < 10) MonthSize=("0" + CalendarMonth + "/");
else MonthSize=(CalendarDate + "/");
if (CalendarDate < 10) DaySize=("0" + CalendarDay + "/");
else DaySize=(CalendarDate + "/");
var TheDateIs = dayname[CalendarDay] + "/" + monthname[CalendarMonth]
+ "/" + CalendarYear
document.write("Todays date is: " + TheDateIs)

</script>
If I change

CalendarDay = aCalendar.getDay();

to:

CalendarDay = aCalendar.getDay()-3;

it displays the correct date. But isn't there a better solution?
I need the date in DD/MM/YYYY format, ie 01/01/2003
Jul 20 '05 #1
6 9818
an****@webmail.co.za (Luis) writes:
I've adapted the following code so that it prints the date in
DD/MM/YYYY format. However it prints the incorrect date! If todays
date is 01/01/2003 it prints 03/01/2003 - 3 days out! What have I done
wrong?
A few problems:

CalendarDay = aCalendar.getDay();
You probably don't need getDay. It returns the number of the day in
the week, not the day in the month.
CalendarYear = aCalendar.getYear();
You might want to use getFullYear if it exists.
var dayname = new Array ("01", "02", "03", "04", "05", "06", "07",
"08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18",
"19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29",
"30", "31" );
with this definition, dayname[1]=="02".
The date object getDate returns the date, and your array is one off,
since it starts at index zero.

Notice that the getMonth method returns the month number minus one,
so January is month zero. Your month array works correctly.
if (CalendarDate < 10) MonthSize=("0" + CalendarMonth + "/");
else MonthSize=(CalendarDate + "/");
If the date is <10 you add a zero in front of the month, else not
in front of the date???

Later, you don't use MonthSize at all.
if (CalendarDate < 10) DaySize=("0" + CalendarDay + "/");
else DaySize=(CalendarDate + "/");
You use Day and Date interchangably. Today is the third, so Date is 3.
It is a Friday, so Day is 5.

Again, you don't use DaySize at all.
var TheDateIs = dayname[CalendarDay] + "/" + monthname[CalendarMonth]
+ "/" + CalendarYear


So this is where you look up the dayname (where you mean datename) by
the week day and one off.

Try this:
---
var aCalendar = new Date();
var theDate = aCalendar.getDate();
if (theDate < 10) {theDate = "0"+theDate;}
var theMonth = aCalendar.getMonth();
if (theMonth<10) {theMonth = "0"+theMonth;}
var theYear;
if (aCalendar.getFullYear) {
theYear = aCalendar.getFullYear(); // use getFullYear if it exists
} else {
theYear = aCalendar.getYear(); // use getYear, add 1900 depending on browser
if (theYear<1900) {
theYear += 1900;
}
}
var TheDateIs = theDate+"/"+theMonth+"/"+theYear;
---

You should seriously consider another format for the date. Neither
dd/mm/yyyy nor mm/dd/yyyy are universally understandable. In an
international setting like the internet, yyyy/mm/dd is much safer.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #2
JRS: In article <fz**********@hotpop.com>, seen in
news:comp.lang.javascript, Lasse Reichstein Nielsen <lr*@hotpop.com>
posted at Fri, 3 Oct 2003 10:58:35 :-
an****@webmail.co.za (Luis) writes:
I've adapted the following code so that it prints the date in
DD/MM/YYYY format. However it prints the incorrect date! If todays
date is 01/01/2003 it prints 03/01/2003 - 3 days out! What have I done
wrong?

Typing. That's 2 days out; your code gives 04/01/2003.

When posting code, do not let your news-reader line-wrap it.

Read the FAQ.
var aCalendar = new Date();
var theDate = aCalendar.getDate();
if (theDate < 10) {theDate = "0"+theDate;}
var theMonth = aCalendar.getMonth() // +1 ?
if (theMonth<10) {theMonth = "0"+theMonth;}
var theYear;
if (aCalendar.getFullYear) {
theYear = aCalendar.getFullYear(); // use getFullYear if it exists
} else {
theYear = aCalendar.getYear(); // use getYear, add 1900 depending on browser
if (theYear<1900) {
theYear += 1900;
}


I don't see the point of all that. If one assumes that getFullYear
might not be implemented (good) but getYear will be (seems safe), and so
codes for getYear, why bother with getFullYear at all? It seems too
far-sighted.

theYear = 1900 + aCalendar.getYear()%1900 // should do, < 3800 AD

--
© 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> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
Jul 20 '05 #3
Dr John Stockton <sp**@merlyn.demon.co.uk> wrote in message news:<Fk**************@merlyn.demon.co.uk>...

When posting code, do not let your news-reader line-wrap it.


Posted via Google Groups so I can't control the wrapping(?)

---

Thanks for the script advice everyone...

For the sake of having a complete thread for the Google archives, I'll
probably go with a variation of the following code as the solution to
the question I posted:

dim TodaysDate, TodaysMonth, TodaysDay

TodaysDate = dateadd("n",application("localoffset"),now())

if len(month(TodaysDate)) = 1 then
TodaysMonth = "0"& month(TodaysDate)
else
TodaysMonth = month(TodaysDate)
end if

if len(day(TodaysDate)) = 1 then
TodaysDay = "0"& day(TodaysDate)
else
TodaysDay = day(TodaysDate)
end if

TodaysDate = year(TodaysDate)& "/"& TodaysMonth& "/"& TodaysDay

This should print: 2003/10/06
Jul 20 '05 #4
JRS: In article <69**************************@posting.google.com >, seen in
news:comp.lang.javascript, Luis <an****@webmail.co.za> posted at Sun, 5 Oct
2003 23:54:10 :-
Dr John Stockton <sp**@merlyn.demon.co.uk> wrote in message news:<FkT9lCAY1df$Ew
OV@merlyn.demon.co.uk>...

When posting code, do not let your news-reader line-wrap it.
Posted via Google Groups so I can't control the wrapping(?)


Non sequitur. You need to put newlines in your code sufficiently often.

Exercise for regulars - how narrow can ECMA-compatible
javascript be written?
---

Thanks for the script advice everyone...

For the sake of having a complete thread for the Google archives, I'll
probably go with a variation of the following code as the solution to
the question I posted:

dim TodaysDate, TodaysMonth, TodaysDay

TodaysDate = dateadd("n",application("localoffset"),now())

if len(month(TodaysDate)) = 1 then
TodaysMonth = "0"& month(TodaysDate)
else
TodaysMonth = month(TodaysDate)
end if

if len(day(TodaysDate)) = 1 then
TodaysDay = "0"& day(TodaysDate)
else
TodaysDay = day(TodaysDate)
end if

TodaysDate = year(TodaysDate)& "/"& TodaysMonth& "/"& TodaysDay

This should print: 2003/10/06


Your if statements could be replaced by use of something like

function LZ(x) {return(x<0||x>9?"":"0")+x}
Your code looks like VBS. My test process dislikes the "dateadd" line;
replacing the function with 3, the result is 1900/01/02, which is proper.
For a change :

with (new Date()) TheDate =
String((getFullYear()*100+getMonth()+1)*100+getDat e()).
replace(/(\d\d)(\d\d)$/, '/$1/$2')

with (new Date()) { setMinutes(getMinutes()+LocalOffset)
TheDate =
String((getFullYear()*100+getMonth()+1)*100+getDat e()).
replace(/(\d\d)(\d\d)$/, '/$1/$2') }

However, javascript has no direct access to LocalOffset;

with (new Date()) TheDate =
String((getUTCFullYear()*100+getUTCMonth()+1)*100+ getUTCDate()).
replace(/(\d\d)(\d\d)$/, '/$1/$2')

--
© 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> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
Jul 20 '05 #5
In article <cl**************@merlyn.demon.co.uk>, Dr John Stockton
<sp**@merlyn.demon.co.uk> writes:
Exercise for regulars - how narrow can ECMA-compatible
javascript be written?


As narrow as the shortest word plus a space or two?
--
Randy
Jul 20 '05 #6
Dr John Stockton <sp**@merlyn.demon.co.uk> writes:
Exercise for regulars - how narrow can ECMA-compatible
javascript be written?


Length of the longest keyword is 10 characters ("instanceof"),
followed by "continue", "function" at 8 characters. I would say ten
characters wide is sufficient. The narrowest *usable* would probably
be four characters, if you don't use the longer keywords. Then
you can create strings containing arbitrary code, and evaluate
it with "eval".

If you use "continue" with a label, I am not sure it can broken into
separate lines. That is "break L" and "continue L" cannot be made
shorter. That still means a ten-character minimum.

For just accessing properties, four characters are sufficient.
You will have to use square bracket notation and cut strings into
small parts to access long property names.

E.g.,
document.getElementById("foo").style.visiblity="vi sible";
can be coded in four-character lines. First we need an object to start
from in order to use square bracket notation, so we write it as

var s=self;
s["document"]["getElementById"]("foo")["style"]["visibility"]="visible";

(Luckily, "self" is shorter than "window")

We then split the strings into lines of at most four characters,
making sure to end each line with an character that prevents semicolon
insertion:

0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123
var s= self ; s[ "d"+ "o"+ "c"+ "u"+ "m"+ "e"+ "n"+
"t" ][ "g"+ "e"+ "t"+ "E"+ "l"+ "e"+ "m"+ "e"+ "n"+ "t"+
"B"+ "y"+ "I"+ "d" ]( "f"+ "o"+ "o" )[ "s"+ "t"+ "y"+
"l"+ "e" ][ "v"+ "i"+ "s"+ "i"+ "b"+ "i"+ "l"+ "i"+ "t"+
"y" ]= "v"+ "i"+ "s"+ "i"+ "b"+ "l"+ "e";

Identifiers-like keywords of four characters ("this","true","null")
can be renamed as
var
x=
this
;
or
var
t=
true
;
The five-character keyword "false" can then be renamed using "!t".
var
f=
!t;
The above lines of four characters on the form "c"+ makes it look like
four is a minimum for composing strings. It isn't. With two extra
variable, you can compose strings with only three characters per line.

var
c;
var
t=
"b"
;
c=
"a"
;
t+=
c;
c=
"z"
;
t+=
c;
f(
t);

Still, you need four characters in order to call "eval" (because
four characters is the shortest possible needed to access the
global object so you can use "eval").
Enough
for
now.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #7

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

Similar topics

1
by: Alfonso Chavez | last post by:
Hi Everybody, I hope this is the correct newsgroup for this, if not please let me know where should i send this question which is driving me crazy. The problem is the FormatDateTime function...
4
by: theintrepidfox | last post by:
Dear Group Some but not all of the dates are incorrect converted (incremented by 1 day) with the following SQL statement. SELECT DISTINCT CONVERT(datetime,cast(ReturnedByDate AS int)) AS...
6
by: Brenda | last post by:
We are currently switching to DB2/AIX. I am modifying my sqrs to work on this new platform. (We are currently on Oracle). I am having a problem with an sqr that has a reference to a variable for...
5
by: m_t_hill | last post by:
Running MS Access 2000 MS Windows XP Pro This has caused me a lot of hair loss in the last few days so would appreciate any help. I am running code to append/update a local access database...
1
by: bonokoot | last post by:
Hello, I wrote this program in C# that accesses a SQL Server database that runs a stored procedure and sents the results in an email every 30min. I wrote this as a windows application instead of a...
4
by: Peter Ritchie | last post by:
Does anyone know how to suppress a specific warning for a line or block of code in C#? C++ has a nice facility to disable a warning for a block of code with #pragma for warnings that are incorrect...
2
by: nightwatch77 | last post by:
Hi, does anyone know why .Net incorrectly handles time zone conversion when passing DateTime through web services? The problem is that it seems to ignore the time zone part. My time zone is CEST,...
6
by: lukasso | last post by:
Hi, this is my code that should produce something like a timetable for a few days with each day divided into 30 minute pieces. It makes query from MySQL and then creates a 2d $array which then is to...
3
Frinavale
by: Frinavale | last post by:
Want to see something weird? The following code: Dim str As New StringBuilder Dim x As String = "11/6/2009 14:00" Dim dx As Date Date.TryParse(x, dx) str.Append("dx:")...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.