473,763 Members | 1,893 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Numeric Date Validation


It has appeared that ancient sources give a method for Numeric Date
Validation that involves numerous tests to determine month length;
versions are often posted by incomers here. That sort of code seems
unnecessarily long.

For some while, the following approach has been given here :-

function ValidDate(y, m, d) { // m = 0..11 ; y m d integers, y!=0
with (new Date(y, m, d))
return (getMonth()==m && getDate()==d) }

and it may remain the shortest code. But it does require, in every
case, the creation and disposal of a Date Object.

The following is about 50% longer in code, but about four times faster
in my system - and it seems to be right, too.

function DateOK(Y, M, D) {
return D>0 && (D<=[,31,28,31,30,31 ,30,31,31,30,31 ,30,31][M] ||
D==29 && M==2 && Y%4==0 && (Y%100>0 || Y%400==0) ) }

Note that checking for 1 <= M <= 12 is inherent, and that the Leapness
of the year is only determined if the date given is February 29th.

Also, it is easy to use only the quadrennial rule if it is certain that
dates are in 1901-2099, or only two rules for 2001-2399.

Comments ? Tests ??

--
© 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.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05
30 3692
JRS: In article <Xn************ ********@194.10 9.133.29>, seen in
news:comp.lang. javascript, Evertjan. <ex************ **@interxnl.net >
posted at Mon, 19 Apr 2004 08:14:28 :

Why this quest for speed?
Do you all want to test an enormous database for false entries?
Usually this test is for human interface validation only, I think,
so speed is not that important.
Seeking efficiency is educational; the training means that one is likely
to achieve greater efficiency when it really matters.

Personally, I would let the system do the thinking for me:

function dateOK(Y,M,D){
var da = new Date(Y,M-1,D)
return Y == da.getFullYear( ) &&
M-1 == da.getMonth() &&
D == da.getDate()
}
AFAICS, only two of those equality tests are needed.

This also checkes for decimals, strings, negatives, etc.
correctly validating strings are allowed, like year '02004',month '3.00'
returns false if year<100


History did not start in the Year 100.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demo n.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #11
JRS: In article <40************ ***@fxmahoney.c om>, seen in
news:comp.lang. javascript, Fox <fo*@fxmahoney. com> posted at Mon, 19 Apr
2004 04:03:46 :
Y should not be negative unless BCE dates, in which case you would add
4712, then perform the leapyear test (but only y % 4 == 0 -- this is why
the Julian calendar got so out of whack over the centuries)
No reason to act as if the Julian Calendar was abandoned in or about the
Year 0.

The new Date object is only valid for the Gregorian calendar: Oct 15,
1582 and forward in time. The "full" year should always be used in the
new Date model. The year 0 is "mapped" to 1900 for "backward
compatibilit y" when the date object would accept 1 or 2 digit years
(pre-y2k). It really doesn't matter that Date supports 2-digit years
since the Gregorian calendar support in Date does not include (accurate
or correct) dates prior to Oct 15, 1582.
No, it covers about +-275000 years from 1970. Before 1582-10-15 (or
possibly 1752-09-14, and much later in Russia) the Gregorian Calendar is
described as proleptic. One only needs to remember that civil dates
have not always been Gregorian.

BTW -- there is *no* year 0 -- the calendar goes from 1 CE to 1 BCE
(going backwards). Year = 0 should be considered invalid (I don't
believe there is even a Day 0 in the Julian calendar -- Day 1 was Jan 1
4713 BCE [plus the Romans did not have a zero digit]).


There is a year 0, between years -1 and +1. A calendar with such years
is called astronomical. Javascript uses it where years are type Number,
but not where they are parts of a full date string.

Neither the Julian nor the Gregorian Calendar has a Day 0; they only
have day counts starting at 1 for each month.

BC 4713-01-01 is the start of the Julian Day/Date [Number] count; but
the start of its Day 1 is noon GMT. Note that it is named for an
entirely different Julian - Scaliger's dad, not the Emperor. See
<URL:http://www.merlyn.demo n.co.uk/moredate.htm#Ju l>, "Which Julian?".

The term Chronological JD can be used for a count starting at the local
midnight which began that solar day.
The Javascript Date Object implements the Astronomical Proleptic
Calendar over a range of exactly +-10^8 days centred on 1970-01-01
00:00:00 GMT - as ECMA-262 requires.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demo n.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #12
JRS: In article <op************ **@news-text.blueyonder .co.uk>, seen in
news:comp.lang. javascript, Michael Winter <M.******@bluey onder.co.invali
d> posted at Mon, 19 Apr 2004 11:41:09 :
Not quite. You are correct that && is before ||, but that makes your
expression incorrect: || needs to be evaluated before && in this case.
Here's how the expression would be evaluated:

((( ayear % 4 ) == 0 ) && (( ayear % 100 ) > 0 )) || (( ayear % 400 ) ==
0 )

simplified to

( !( ayear % 4 ) && ( ayear % 100 )) || !( ayear % 400 )

Notice the difference between the one above, and mine (and Dr Stockton's)
below.

One needs to test.

I believe that the numbers should appear in the order 4 100 400, to make
the best use of short-circuit evaluation possible.

But the three "%" results are not independent; there are only four types
of year number , not eight. Thus there is not necessarily a unique
combination of order-of-operation required for the right result.

Your preference may be - doubtless is - right; but that does not mean
that all other preferences give the wrong answer.

--
© 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.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #13
Dr John Stockton wrote on 19 apr 2004 in comp.lang.javas cript:
function dateOK(Y,M,D){
var da = new Date(Y,M-1,D)
return Y == da.getFullYear( ) &&
M-1 == da.getMonth() &&
D == da.getDate()
}


AFAICS, only two of those equality tests are needed.


That would not be very educational.
This also checkes for decimals, strings, negatives, etc.
correctly validating strings are allowed, like year '02004',month
'3.00' returns false if year<100


History did not start in the Year 100.


Why confine onself merely to history, what about prehistoric dates ?

==============

These sub 100 year inputs can be expanded
to the "nearest" 4 digit year numbers

[again intentionally educationally non optimized]:

if (Y>=0 && Y<35) Y += 2000
if (Y>=35 && Y<100) Y += 1900
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jul 23 '05 #14
On Mon, 19 Apr 2004 21:55:17 +0100, Dr John Stockton
<sp**@merlyn.de mon.co.uk> wrote:
JRS: In article <op************ **@news-text.blueyonder .co.uk>, seen in
news:comp.lang. javascript, Michael Winter
<M.******@bluey onder.co.invali d> posted at Mon, 19 Apr 2004 11:41:09 :
Not quite. You are correct that && is before ||, but that makes your
expression incorrect: || needs to be evaluated before && in this case.
Here's how the expression would be evaluated:

((( ayear % 4 ) == 0 ) && (( ayear % 100 ) > 0 )) || (( ayear % 400 )
==
0 )

simplified to

( !( ayear % 4 ) && ( ayear % 100 )) || !( ayear % 400 )

Notice the difference between the one above, and mine (and Dr
Stockton's) below.
One needs to test.


Probably. :)
I believe that the numbers should appear in the order 4 100 400, to make
the best use of short-circuit evaluation possible.

But the three "%" results are not independent; there are only four types
of year number , not eight. Thus there is not necessarily a unique
combination of order-of-operation required for the right result.

Your preference may be - doubtless is - right; but that does not mean
that all other preferences give the wrong answer.


When I first wrote my response, I was comparing the order of evaluation to
the form you presented (which is the same form I remember seeing from
other sources). It was a blind comparison. I did think later that the
order might not be quite so important.

This sort of thing occurs more often than I'd like, but as I hadn't
reached a conclusion, I hadn't sought to make another post.

A simple test, taking years from 0 to 10000[1], shows no difference in
result. However, there is a *very* slight difference in execution time,
which makes mine faster (even when forcing the result to boolean using
!!(expr)).

Mike
[1] I realise that a reasoned choice would be more desirable, but it
should suffice.

--
Michael Winter
M.******@blueyo nder.co.invalid (replace ".invalid" with ".uk" to reply)
Jul 23 '05 #15
Hold on a sec. First of all, your expression (Method 1)
( !( ayear % 4 ) && ( ayear % 100 )) || !( ayear % 400 )


is saying a year is a leap year iff
((it's divisible by 4) AND (it's not divisible by 100)) OR
(it's divisible by 400).

But that's the same as (Method 2):
a year is a leap year iff
(it's divisible by 4) AND ((it's not divisible by 100) OR
(it's divisible by 400))

In other words, from a logical point of view, you don't
NEED the grouping parentheses. But they DO make
a difference (theoretically, anyway. YOU can do the testing).
Let's just check out how many times each condition gets
executed.

Method 1:
Year not divisible by 4: first and last expressions
Year divisible by 4/ not by 100: first two
Year divisible by 400: all three

Method 2:
Year not divisible by 4: first one only
Year divisible by 4/ not by 100: first two
Year divisible by 400: all three

So in 75% of all cases, Method 2 will have only one test
to two for Method 1.

But wait, there's more. Since you've come to the right
newsgroup, tonight only, we'll throw in a special simplification,
to get rid of not one, but two of those pesky modulo operators.
Who needs extra divisions, after all? So here you have it -
Method 2, simplified:

isLeapYear = !( ayear & 3 ) && (( ayear % 25 != 0 ) || !( ayear & 15 ))
From Bit Tiddle City,
Csaba Gabor

PS. If you leave out the != 0 part in the second condition, your result
in the case of leap years not divisible by 400 will be numeric (nonzero -
the result of ayear % 25) instead of boolean true, which would be OK
for most of my purposes.
Jul 23 '05 #16
On Tue, 20 Apr 2004 03:53:04 +0200, Csaba Gabor <ne**@CsabaGabo r.com>
wrote:
Hold on a sec. First of all, your expression (Method 1)
Actually, my expression was method 2. The first two expressions I stated
were representations of Dennis' test once operator precedence was applied.
My proposed expression was the last in my first post.
( !( ayear % 4 ) && ( ayear % 100 )) || !( ayear % 400 )


is saying a year is a leap year iff
((it's divisible by 4) AND (it's not divisible by 100)) OR
(it's divisible by 400).

But that's the same as (Method 2):
a year is a leap year iff
(it's divisible by 4) AND ((it's not divisible by 100) OR
(it's divisible by 400))

In other words, from a logical point of view, you don't
NEED the grouping parentheses. But they DO make
a difference (theoretically, anyway. YOU can do the testing).
Let's just check out how many times each condition gets
executed.

Method 1:
Year not divisible by 4: first and last expressions
Year divisible by 4/ not by 100: first two
Year divisible by 400: all three

Method 2:
Year not divisible by 4: first one only
Year divisible by 4/ not by 100: first two
Year divisible by 400: all three

So in 75% of all cases, Method 2 will have only one test
to two for Method 1.


I hadn't thought about it before (I was just rattling off code without
much thought, as I said earlier), but during testing I noticed that not
all results were boolean. When I examined the expression, I came to your
same conclusion.
But wait, there's more. Since you've come to the right
newsgroup, tonight only, we'll throw in a special simplification,
to get rid of not one, but two of those pesky modulo operators.
Who needs extra divisions, after all? So here you have it -
Method 2, simplified:

isLeapYear = !( ayear & 3 ) && (( ayear % 25 != 0 ) || !( ayear & 15 ))


I realised that Dr Stockton was indicating more than what I responded to,
but I was too tired to consider what. My (still) tired brain thanks you. :)

The first bitwise operation was obvious in its effect (a common enough
optimisation), but I couldn't think why the third was using 15. I then
noticed you changed the second to 25. A prime example of why I normally
avoid thinking too hard in the morning.

Mike
[1] I didn't expect && to operate the same way as || for non-boolean
types. Not having used it in that manner before, whereas I often use ||
for setting default values, I don't suppose there was much reason to.

--
Michael Winter
M.******@blueyo nder.co.invalid (replace ".invalid" with ".uk" to reply)
Jul 23 '05 #17
JRS: In article <Xn************ *******@194.109 .133.29>, seen in
news:comp.lang. javascript, Evertjan. <ex************ **@interxnl.net >
posted at Mon, 19 Apr 2004 22:43:50 :
Why confine onself merely to history, what about prehistoric dates ?
Javascript will handle back past BC 270000, using proleptic Gregorian;
my site has the essentials for Julian. "Actual" calendars other than
those are either too troublesome or not interesting enough, though I
have some Hebrew calendar stuff in Pascal.

These sub 100 year inputs can be expanded
to the "nearest" 4 digit year numbers

[again intentionally educationally non optimized]:

if (Y>=0 && Y<35) Y += 2000
if (Y>=35 && Y<100) Y += 1900

But some people will actually want to refer to years before AD 100.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demo n.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #18
JRS: In article <op************ **@news-text.blueyonder .co.uk>, seen in
news:comp.lang. javascript, Michael Winter <M.******@bluey onder.co.invali
d> posted at Mon, 19 Apr 2004 23:12:30 :
A simple test, taking years from 0 to 10000[1], shows no difference in
result. However, there is a *very* slight difference in execution time,
which makes mine faster (even when forcing the result to boolean using
!!(expr)). [1] I realise that a reasoned choice would be more desirable, but it
should suffice.


Since the Calendar repeats every 400 years, 1 to 10000 would be better,
but only in principle.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demo n.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #19
JRS: In article <40******@andro meda.datanet.hu >, seen in
news:comp.lang. javascript, Csaba Gabor <ne**@CsabaGabo r.com> posted at
Tue, 20 Apr 2004 03:53:04 :
isLeapYear = !( ayear & 3 ) && (( ayear % 25 != 0 ) || !( ayear & 15 ))
!( ayear & 3 || !( ayear & 15 ) && ayear % 25 )

omits the != 0 but still gives a Boolean result in every case; it has
the same number of other operations.
Now tested in <URL:http://www.merlyn.demo n.co.uk/js-date4.htm#MaYL> , but
not timed.
From Bit Tiddle City,


Tiddle != Twiddle

--
© 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.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #20

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

Similar topics

4
3955
by: Gezeala 'Eyah' Bacu\361o II | last post by:
hey guys..need your help on this.. i have a plpgsql function where in i compute numeric values for my php scripts.. my problem is my function just won't round some numbers properly.. what i want it to do is like this. example:
0
1993
by: Brian Conway | last post by:
I am having some validation and insertion problems. I am using a date picker that takes the selected date and puts it to ("dd-MMM-yyyy") format, as this was the only format that Oracle would accept on an insert, however, when it does a comparision validation it is failing. I have StartDate = comparing to an invisible textbox that contains todays date EndDate = comparing to StartDate needing to be >= SetupDate = comparing to StartDate...
7
10311
by: Paul | last post by:
Hi, I have a form where a user is required to enter a start date and an end date. Both are required and must between a specific date range (e.g. 01/01/1900 and 01/01/2099) and the end date cannot preceed the start date. How can I perform the necessary validation using the least number of validation controls. For example is it necessary that I add a requiredfieldvalidator for the start date field and end date field to make sure a value...
7
31839
by: James P. | last post by:
Hello there, In my asp.net page using VB, I have a date text field in mm/dd/yyyy format. When a date is entered, I'd like to validate it to make sure the date is greater than or equal to the current date. If not, I'd like to display the error message to ValidationSummary. It seems to make sense to me to use CompareValidator but the problem is put the current date into CompareValidator. So, I created a hidden text field in my aspx. ...
12
3287
by: Diego | last post by:
Can I validate (possibly with a compare validator) a Date entered by the user based upon his regional settings? I.e. if a user is american the format would be mm/dd/yyyy, if brittish dd/mm/yyyy Thanks, Diego.
2
2917
by: Chad | last post by:
I have a textbox control, txtMeasurement, that I want to allow only numeric decimal input. I thought to use a client side validation control to ensure that the data entered is of type "Double". 'Measurement Validation (Range Validator) Dim MeasurementRangeValidator As New RangeValidator 'validate that the measure is numeric MeasurementRangeValidator.ControlToValidate = txtMeasurement.ID| MeasurementRangeValidator.Display =...
2
9110
by: craig.wagner | last post by:
I have an element in my schema defined as follows: <xs:element name="BillingDate" type="xs:dateTime" nillable="true" minOccurs="0"/> I use the schema to validate incoming documents using an XmlValidatingReader in .NET 1.1. If the document contains the above element with no data, for example:
16
12207
by: tshad | last post by:
I have a string field and a decimal fields and was wondering what the best way to check for numeric is? I have to do something like: If (myAmount is numeric) { total += myAmount; }
0
10149
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
10003
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...
0
9828
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
8825
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
7370
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
6643
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
5410
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3529
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2797
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.