473,722 Members | 2,240 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6978
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**@discussio ns.microsoft.co m> wrote in message
news:2B******** *************** ***********@mic rosoft.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**@discussio ns.microsoft.co m> 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".ToCharArr ay();
static readonly char[] UpperBounds = "19/39/2999".ToCharArr ay();
static bool IsProbablyValid Date(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.ParseE xact) 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.Reg ularExpressions ;
using System.Globaliz ation;

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(T estRegex));
Time (new MethodInvoker(T estHardCoded));
Time (new MethodInvoker(T estNoPreCheck)) ;
}

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

Console.WriteLi ne ("{0}: {1}", test.Method.Nam e, end-start);
}

static readonly Regex Expression = new Regex
(@"\d{1,2}\/\d{1,2}\/\d{4}", RegexOptions.Co mpiled);
static void TestRegex()
{
for (int i=0; i < Iterations; i++)
{
foreach (string x in invalid)
{
if (Expression.IsM atch(x))
{
try
{
DateTime.ParseE xact(x, "dd/mm/yyyy",
CultureInfo.Inv ariantCulture);
throw new Exception("Inva lid date passed");
}
catch
{
}
}
}
foreach (string x in valid)
{
if (Expression.IsM atch(x))
{
try
{
DateTime.ParseE xact(x, "dd/mm/yyyy",
CultureInfo.Inv ariantCulture);

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

static void TestHardCoded()
{
for (int i=0; i < Iterations; i++)
{
foreach (string x in invalid)
{
if (IsProbablyVali dDate(x))
{
try
{
DateTime.ParseE xact(x, "dd/mm/yyyy",
CultureInfo.Inv ariantCulture);

throw new Exception("Inva lid date passed");
}
catch
{
}
}
}
foreach (string x in valid)
{
if (IsProbablyVali dDate(x))
{
try
{
DateTime.ParseE xact(x, "dd/mm/yyyy",
CultureInfo.Inv ariantCulture);

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

static void TestNoPreCheck( )
{
for (int i=0; i < Iterations; i++)
{
foreach (string x in invalid)
{
try
{
DateTime.ParseE xact(x, "dd/mm/yyyy",
CultureInfo.Inv ariantCulture);
throw new Exception("Inva lid date passed");
}
catch
{
}
}
foreach (string x in valid)
{
try
{
DateTime.ParseE xact(x, "dd/mm/yyyy",
CultureInfo.Inv ariantCulture);
}
catch
{
throw new Exception("Vali d date failed");
}
}
}
}

static readonly char[] LowerBounds = "00/00/1000".ToCharArr ay();
static readonly char[] UpperBounds = "19/39/2999".ToCharArr ay();
static bool IsProbablyValid Date(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.343750 0
TestHardCoded: 00:00:04.343750 0
TestNoPreCheck: 00:00:12.515625 0

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.co m>
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**********@p lanet.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.Visua lBasic.dll
assembly, and then add

using Microsoft.Visua lBasic;

at the top of the source file, then use

Information.IsD ate(foo);

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

--
Jon Skeet - <sk***@pobox.co m>
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.Visua lBasic.dll
assembly, and then add

using Microsoft.Visua lBasic;

at the top of the source file, then use

Information.IsD ate(foo);

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

Jul 21 '05 #6
Cor Ligthert <no**********@p lanet.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.co m>
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.ParseE xact.

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.Visua lBasic 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**********@p lanet.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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #10

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

Similar topics

15
14281
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" DateTime.Now.AddMinutes(90) returns "1:30" or "01:30"
38
807
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 FormatString, how can you convert the String back to a DateTime? DateTime.Parse(...) doesn't use the FormatString. Now admitedly, if the format string is just "MM", it can't be done. But if the format string is "yyyyMMdd", or "ddMMMyyyy hhmmsst", it...
26
2679
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' How do i do that? Reny ---
11
7241
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 only that I have to listen to them because they know it better. They told also that in a business situation it is better to use datetime.parseexact for changing cultures and not to use the globalization setting. I did not give them this sample,...
15
1962
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 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...
1
12861
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! Format String: "yyyymmdd" Date Value: "01/01/2006"
5
5140
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. Could someone help me with the customization? Thanks. String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.DateTime.Parse(String s, IFormatProvider...
1
15346
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 exception. Is there a better way? Notice also my use of a dummy dateTime object. Also, does the DateTime object contain any information about how it should be formatted? For example - "Format Error: DateTime cell incorrectly formatted. Expected...
0
8863
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
8739
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
9384
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
9238
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
9088
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...
1
6681
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
4502
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
4762
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2147
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.