473,320 Members | 1,829 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.

Check DateTime format

My application asks the user to enter in a date - in the mm/dd/yyyy format. Is there any quick and easy way to verify the date the user enters is formatted correctly? Right now I'm calling DateTime.Parse() and catching the FormatException but it seems this is a bit inefficient - catching the exception that is. There is some pretty obvious delay while it traces back up the call stack. Is there a better way? Something that returns a bool possibly?

--
Dan S
Jul 21 '05 #1
15 6935
Hi,

To just check the format you may use regular expressions like
\d{1,2}\/\d{1,2}\/\d{4}. If this validates, use DateTime.Parse() to check
the actual values.
"Dan S" <Da**@discussions.microsoft.com> wrote in message
news:2B**********************************@microsof t.com...
My application asks the user to enter in a date - in the mm/dd/yyyy format.
Is there any quick and easy way to verify the date the user enters is
formatted correctly? Right now I'm calling DateTime.Parse() and catching
the FormatException but it seems this is a bit inefficient - catching the
exception that is. There is some pretty obvious delay while it traces back
up the call stack. Is there a better way? Something that returns a bool
possibly?

--
Dan S
Jul 21 '05 #2
Dan S <Da**@discussions.microsoft.com> wrote:
My application asks the user to enter in a date - in the mm/dd/yyyy
format. Is there any quick and easy way to verify the date the user
enters is formatted correctly? Right now I'm calling DateTime.Parse()
and catching the FormatException but it seems this is a bit
inefficient - catching the exception that is. There is some pretty
obvious delay while it traces back up the call stack. Is there a
better way? Something that returns a bool possibly?


After the first time, which may involve a delay due to loading
resources, throwing an exception is likely to be very fast - far faster
than a user can actually notice. On my laptop I can throw a hundred
thousand exceptions in a second - I think that's rather more than a
user is likely to enter.

I'm not saying that exceptions are always a nice way to go, but I
wouldn't dismiss them for performance reasons - at least not in this
case.

You can use a regular expression to check the format, of course - but
you may well find that doing so is more expensive than just trying to
parse the date and catching the exception.

You could probably do slightly better with a hard-coded test, something
like:

static readonly char[] LowerBounds = "00/00/1000".ToCharArray();
static readonly char[] UpperBounds = "19/39/2999".ToCharArray();
static bool IsProbablyValidDate(string date)
{
if (date.Length != 10)
{
return false;
}
for (int i=0; i < date.Length; i++)
{
char c=date[i];
if (c < LowerBounds[i] || c > UpperBounds[i])
{
return false;
}
}
return true;
}

That gets rid of *many* invalid dates, but not all - you'll still need
to call DateTime.Parse (or preferrably DateTime.ParseExact) and catch
the potential exception, unless you want to do all the parsing
correctly.

Note that it also requires the leading zeroes for months and days - if
you don't want that, it becomes slightly trickier.

(That only deals with dates in years 1000-2999; if you need to deal
with earlier or later years, change the 7th character in
LowerBounds/UpperBounds.)

Here's a benchmark to compare the three approaches mentioned:

using System;
using System.Windows.Forms; // For MethodInvoker
using System.Text.RegularExpressions;
using System.Globalization;

delegate void DoSomething();

class Test
{
static string[] invalid = {"123123", "wibble", "32/12/3223",
"14/23/1999", "04/35/1992", "02/29/2003"};

static string[] valid = {"12/02/2321", "02/12/2312", "02/29/2004",
"01/30/2000"};

const int Iterations = 100000;

static void Main()
{
Time (new MethodInvoker(TestRegex));
Time (new MethodInvoker(TestHardCoded));
Time (new MethodInvoker(TestNoPreCheck));
}

static void Time(MethodInvoker test)
{
DateTime start = DateTime.Now;
test();
DateTime end = DateTime.Now;

Console.WriteLine ("{0}: {1}", test.Method.Name, end-start);
}

static readonly Regex Expression = new Regex
(@"\d{1,2}\/\d{1,2}\/\d{4}", RegexOptions.Compiled);
static void TestRegex()
{
for (int i=0; i < Iterations; i++)
{
foreach (string x in invalid)
{
if (Expression.IsMatch(x))
{
try
{
DateTime.ParseExact(x, "dd/mm/yyyy",
CultureInfo.InvariantCulture);
throw new Exception("Invalid date passed");
}
catch
{
}
}
}
foreach (string x in valid)
{
if (Expression.IsMatch(x))
{
try
{
DateTime.ParseExact(x, "dd/mm/yyyy",
CultureInfo.InvariantCulture);

}
catch
{
throw new Exception("Valid date failed");
}
}
else
throw new Exception("Valid date failed");
}
}
}

static void TestHardCoded()
{
for (int i=0; i < Iterations; i++)
{
foreach (string x in invalid)
{
if (IsProbablyValidDate(x))
{
try
{
DateTime.ParseExact(x, "dd/mm/yyyy",
CultureInfo.InvariantCulture);

throw new Exception("Invalid date passed");
}
catch
{
}
}
}
foreach (string x in valid)
{
if (IsProbablyValidDate(x))
{
try
{
DateTime.ParseExact(x, "dd/mm/yyyy",
CultureInfo.InvariantCulture);

}
catch
{
throw new Exception("Valid date failed");
}
}
else
throw new Exception("Valid date failed");
}
}
}

static void TestNoPreCheck()
{
for (int i=0; i < Iterations; i++)
{
foreach (string x in invalid)
{
try
{
DateTime.ParseExact(x, "dd/mm/yyyy",
CultureInfo.InvariantCulture);
throw new Exception("Invalid date passed");
}
catch
{
}
}
foreach (string x in valid)
{
try
{
DateTime.ParseExact(x, "dd/mm/yyyy",
CultureInfo.InvariantCulture);
}
catch
{
throw new Exception("Valid date failed");
}
}
}
}

static readonly char[] LowerBounds = "00/00/1000".ToCharArray();
static readonly char[] UpperBounds = "19/39/2999".ToCharArray();
static bool IsProbablyValidDate(string date)
{
if (date.Length != 10)
{
return false;
}
for (int i=0; i < date.Length; i++)
{
char c=date[i];
if (c < LowerBounds[i] || c > UpperBounds[i])
{
return false;
}
}
return true;
}
}

The results on my laptop were:
TestRegex: 00:00:09.3437500
TestHardCoded: 00:00:04.3437500
TestNoPreCheck: 00:00:12.5156250

Changing the regex to require exactly two digits instead of 1 or 2 for
the month and day sped it up very slightly, but not really
significantly.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #3
Hi Dan,

Probably you are using C# because you write so nice your DateTme.Parse().

However when you use VBNet you can use this.
http://msdn.microsoft.com/library/de...afctisdate.asp
Cor
My application asks the user to enter in a date - in the mm/dd/yyyy format. Is there any quick and easy way to verify the date the user enters
is formatted correctly? Right now I'm calling DateTime.Parse() and catching
the FormatException but it seems this is a bit inefficient - catching the
exception that is. There is some pretty obvious delay while it traces back
up the call stack. Is there a better way? Something that returns a bool
possibly?

Jul 21 '05 #4
Cor Ligthert <no**********@planet.nl> wrote:
Probably you are using C# because you write so nice your DateTme.Parse().

However when you use VBNet you can use this.
http://msdn.microsoft.com/library/de...ary/en-us/vblr
7/html/vafctisdate.asp


In fact, you can use that from within C# as well, if you really want to
(although personally I'd recommend against using it).

You just need to add a reference to the Microsoft.VisualBasic.dll
assembly, and then add

using Microsoft.VisualBasic;

at the top of the source file, then use

Information.IsDate(foo);

However, I very much doubt that that would be any faster than a
straight try/catch round DateTime.ParseExact.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #5
Hi Jon,

I stuffed this row from the message while I was afraid to offend you.

\\\
As Jon often write it can be used in C# as well, when you want maybe he can
than give you the proper code.
///

:-)

Cor
Probably you are using C# because you write so nice your DateTme.Parse().
However when you use VBNet you can use this.
http://msdn.microsoft.com/library/de...ary/en-us/vblr
7/html/vafctisdate.asp


In fact, you can use that from within C# as well, if you really want to
(although personally I'd recommend against using it).

You just need to add a reference to the Microsoft.VisualBasic.dll
assembly, and then add

using Microsoft.VisualBasic;

at the top of the source file, then use

Information.IsDate(foo);

However, I very much doubt that that would be any faster than a
straight try/catch round DateTime.ParseExact.

Jul 21 '05 #6
Cor Ligthert <no**********@planet.nl> wrote:
I stuffed this row from the message while I was afraid to offend you.

\\\
As Jon often write it can be used in C# as well, when you want maybe he can
than give you the proper code.
///


LOL - certainly no offence taken. I just don't think it's any better to
use the VB function than to write their equivalent in "straight" .NET
code :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #7
Jon,

For me is a try catch the same as a late binding, when it is for in advance
catchable error handling, it should be avoided.

However just my opinion.

Cor
However, I very much doubt that that would be any faster than a
straight try/catch round DateTime.ParseExact.

Jul 21 '05 #8
> >
\\\
As Jon often write it can be used in C# as well, when you want maybe he can than give you the proper code.
///


LOL - certainly no offence taken. I just don't think it's any better to
use the VB function than to write their equivalent in "straight" .NET
code :)

When you had not written that "straight" I would not have answered on this.
You mean with this *the not "straight" .Net* the simple basic namespace
without those very well intressing extentions as in the
Microsoft.VisualBasic namespace.

However I agree with you that it is not right to use that function in C#
with the VB namespace. That difficult it cannot be to write it yourself as
your own class.

Cor
Jul 21 '05 #9
Cor Ligthert <no**********@planet.nl> wrote:
For me is a try catch the same as a late binding, when it is for in advance
catchable error handling, it should be avoided.

However just my opinion.


You seem to make an assumption that the VB function won't have a
try/catch inside it. I suspect that's not the case. A try/catch inside
someone else's method is going to take just as long as a try/catch
inside your own method...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #10
> You seem to make an assumption that the VB function won't have a
try/catch inside it. I suspect that's not the case. A try/catch inside
someone else's method is going to take just as long as a try/catch
inside your own method...


No a try catch can used everywhere so as well in a method in the VB
namespace however I think that it is not nice programming to use them for an
error which can be evaluated without to use that.

I said, my opinion.

Cor
Jul 21 '05 #11
Cor Ligthert <no**********@planet.nl> wrote:
LOL - certainly no offence taken. I just don't think it's any better to
use the VB function than to write their equivalent in "straight" .NET
code :)
When you had not written that "straight" I would not have answered on this.
You mean with this *the not "straight" .Net* the simple basic namespace
without those very well intressing extentions as in the
Microsoft.VisualBasic namespace.
Not entirely sure what you mean there, but I don't count using
Microsoft.VisualBasic namespace as writing "straight" .NET code. The
namespace is not documented under the main framework documentation -
it's only documented under the VB documentation, and it doesn't even
appear if you have the C# filter on. Sure, the assembly is probably
written entirely in .NET itself, but it's not part of the main
framework in my view.
However I agree with you that it is not right to use that function in C#
with the VB namespace. That difficult it cannot be to write it yourself as
your own class.


Um, I think I agree, depending on exactly what you mean.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #12
Cor Ligthert <no**********@planet.nl> wrote:
For me is a try catch the same as a late binding, when it is for in advance
catchable error handling, it should be avoided.


Just for fun, I included using Information.IsDate in the benchmark
posted earlier. Here's the appropriate method:

static void TestIsDate()
{
for (int i=0; i < Iterations; i++)
{
foreach (string x in invalid)
{
if (Information.IsDate(x))
{
try
{
DateTime.ParseExact(x, "dd/mm/yyyy",
CultureInfo.InvariantCulture);
throw new Exception("Invalid date passed");
}
catch
{
}
}
}
foreach (string x in valid)
{
if (Information.IsDate(x))
{
try
{
DateTime.ParseExact(x, "dd/mm/yyyy",
CultureInfo.InvariantCulture);
}
catch
{
throw new Exception("Valid date failed");
}
}
else
throw new Exception("Valid date failed: "+x);
}
}
}

The additional call to DateTime.ParseExact is required if you want to
actually *get* the date. If you don't, and you trust IsDate completely,
the performance will obviously be better.

It only worked after setting the current culture of the current thread
to US:

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture
("en-US");

Results:
With DateTime.ParseExact as well: 27.53s
Without DateTime.ParseExact : 25.97s

So using the VB libraries is about 5 times slower than using a hard-
coded method, and requires extra changes to the running environment.
It's also over twice as slow as just using try/catch directly.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #13
Cor Ligthert <no**********@planet.nl> wrote:
You seem to make an assumption that the VB function won't have a
try/catch inside it. I suspect that's not the case. A try/catch inside
someone else's method is going to take just as long as a try/catch
inside your own method...


No a try catch can used everywhere so as well in a method in the VB
namespace however I think that it is not nice programming to use them for an
error which can be evaluated without to use that.

I said, my opinion.


I fail to see why writing your own method which uses try/catch is any
better than using a VB function which probably uses try/catch and
performs significantly worse than other alternatives. (See my other
post for performance figures.) Why is a try/catch buried in someone
else's code any better than a try/catch buried in yours? (You don't
have to have it everywhere - just in the method where you implement the
parsing/testing.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #14
Jon,

I only wrote that in my opinion using a try and catch, for things that can
be catched in advance with code, should be avoided.

That does not mean that I did not believe you about the performance, the
code for testing a date can be very long, I did not even try to write an
example.

When I disagree with you about something, I write that, I think that you
have enough expirience with that. And when not there is no need to prove it
for me.

Maybe you think only C# people have principles, no it is not.

:-)

Cor
Jul 21 '05 #15
Cor Ligthert <no**********@planet.nl> wrote:
I only wrote that in my opinion using a try and catch, for things that can
be catched in advance with code, should be avoided.
And I agree with that. However, your post *seemed* to suggest to me
that you would rather call IsDate than use a try/catch, despite the
fact that IsDate almost certainly contains a try/catch. Were you not
actually suggesting that using IsDate is better?
That does not mean that I did not believe you about the performance, the
code for testing a date can be very long, I did not even try to write an
example.

When I disagree with you about something, I write that, I think that you
have enough expirience with that. And when not there is no need to prove it
for me.

Maybe you think only C# people have principles, no it is not.


I certainly don't think that.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #16

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

Similar topics

15
by: Fritz Switzer | last post by:
I'd like to have a string assigned the value of a DateTime.AddMinutes(amount) so that the string is formatted in "HH:MM" format. For example: DateTime.Now.AddMinutes(30) returns "00:30" ...
38
by: nobody | last post by:
I know that given a FormatString and a DateTime you can use DateTime.ToString(...) to convert the DateTime to a String. My question is how can you turn that around? Given a String and a...
26
by: Reny J Joseph Thuthikattu | last post by:
Hi, I have a variabe in the format of 'DD-MON-YYYY HH:MI AM' .I want to add a miniute to it.How can i do that? by manipulation i want to make '01-JUNE-2004 11:59 PM' to '02-JUNE-2004 12:00 AM'...
11
by: Cor Ligthert | last post by:
Hello everybody, Jay and Herfried are telling me every time when I use CDate that using the datetime.parseexact is always the best way to do String to datetime conversions. They don't tell why...
15
by: Dan S | last post by:
My application asks the user to enter in a date - in the mm/dd/yyyy format. Is there any quick and easy way to verify the date the user enters is formatted correctly? Right now I'm calling...
1
by: Thomas | last post by:
Hi all, i have to check if a value is a valid date format depending on a "format string" the user specified. For example: Format String: "dd/mm/yyyy" Date Value: "01/12/2006" Valid: Yes! ...
5
by: js | last post by:
I have a textbox contains text in the format of "yyyy/MM/dd hh:mm:ss". I need to parse the text using System.DateTime.Parse() function with custom format. I got an error using the following code. ...
1
by: Magnus.Moraberg | last post by:
Hi, I have the following event which checks if a cell in a dgv contains a date and if so, checks if it is formatted correctly. I don't think its good practice for be to try this by catching an...
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
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...
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...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
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...
1
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: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.