regex to check datetime with a runtime exception - c#

#"(Sun|Mon|Tue|Wed|Thu|Fri|Sat)\,((31(?!\ (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\b|t)t?|Nov)(ember)?)))|((30|29)(?!\ Feb(ruary)?))|(29(?=\ Feb(ruary)?\ (((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\d|2[0-8])\ (Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|Jul(y)?)|Aug(ust)?|Oct(ober)?|(Sep(?=\b|t)t?|Nov|Dec)(ember)?)\((1[6-9]|[2-9]\d)\d{2})\s(20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d"
Hello, I use it to check for datetime formated as
Thu, 10 Nov 2010 13:08:06
I have runtime exception stating that is an invalid regex.

You should use DateTime.TryParse(). It's more suited to your needs.

Since you've tagged this with PHP...
You could use strtotime(); to convert the string to a timestamp, then create the date required in the correct format, as follows:
date("D, j M Y H:i:s", strtotime("Thu, 10 Nov 2010 13:08:06"));
Then at least however it is written, it will be converted correctly (belongs as the date is (of course) valid.
Just an alternative to regex....

This compiles :
Regex regexObj = new Regex(#"(Sun|Mon|Tue|Wed|Thu|Fri|Sat),((31(?! (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\b|t)t?|Nov)(ember)?)))|((30|29)(?! Feb(ruary)?))|(29(?= Feb(ruary)? (((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\d|2[0-8]) (Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|Jul(y)?)|Aug(ust)?|Oct(ober)?|(Sep(?=\b|t)t?|Nov|Dec)(ember)?\((1[6-9]|[2-9]\d)\d{2}\s(20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d");
You have a couple of two many ). Other than that, good luck debugging this mess..

Related

Re-format datetime to 7th November 2014

I have myself a DateTime variable of
7/11/2014
and I want to convert that date to display as
7th November 2014
What format do I use? I have tried ToLongDateString but it misses the suffix of the day date.
I don't believe there's any direct support for ordinals ("st", "nd", "th") within .NET. If you only need to support English, I suggest you hard code it yourself. For example:
string text = string.Format("{0}{1} {2} {3}", dt.Day, GetOrdinal(dt.Day),
dt.ToString("MMMM"), dt.Year);
(Where you'd write GetOrdinal yourself.) Note that this assumes you want exactly this format - different cultures (even within English) may prefer November 7th 2014 for example.
If you need to support all kinds of languages, it becomes very difficult - different languages have some very different approaches to ordinals.
Side-note: Even Noda Time doesn't handle this yet. I hope to eventually implement some CLDR support, which should in theory handle it for all locales. We'll see...

Removing Timezone for DateTime.ParseExact

I am trying to parse a string into a datetime with the following format:
[Day],[Date] [Month] [Year] [Time][am/pm] [timezone] (example:)
"Thursday, 1 Dec 2011 08:30pm EST"
I've done this using a DateTime.ParseExact with the format("dddd, dd MMM yyyy hh:mmtt"). However the timzone is giving me an issue. There is no code for reading the timezone written in that manner. I don't care about the timezone anyway, so I want to either strip it out or read it - as long as the parsexact will work.
One way of removing it is to actually remove it from the string (using .Replace) - however I don't know how many different timezones the source will produce, and anyway I think a long line of replace looks ugly and error-prone.
So is there a way of either removing it, or reading it (and then I can ignore it) ?
You can scan the string for spaces, and cut everything after the fifth space. If there are only four spaces, keep the entire string (this means that there is no timezone).
This answer has been edited after a comment by Jon.

The string was not recognized as a valid DateTime. There is an unknown word starting at index 0

I have the following C# that is giving me the error above when trying to parse string to datetime.
DateTime backupdate = System.Convert.ToDateTime(imageflowlabel.Text);
DateTime currentdate = System.DateTime.Now.AddHours(-2);
int result = currentdate.CompareTo(backupdate);
imageflowlable.text looks like this 2012-04-15 15:23:34:123
Any ideas on how to convert this?
Thanks
Yes - use "DateTime.ParseExact()" or "TryParseExact()" with a custom format string:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
DateTime currentdate;
int result;
try
{
// EXAMPLE: 2012-04-15 15:23:34:123
DateTime backupdate =
DateTime.ParseExact (
"yyyy-MM-dd HH:mm:ss:fff", //mind the casing
imageflowlabel.Text,
CultureInfo.InvariantCulture);
currentdate = System.DateTime.Now.AddHours(-2);
result = currentdate.CompareTo(backupdate);
}
catch (Exception ex)
{
...
Your problem is with the time part of your dateTime string. If your string read "2012-04-15 15:23:34.123" then it would work. You could modify your string and replace the last colon with a period and that would fix it.
Your code looks correct; the issue is presumably with your string format, whose last : should actually be a . (indicating the start of the fractional seconds).
Incorrect: 2012-04-15 15:23:34:123
Correct: 2012-04-15 15:23:34.123
Convert.ToDateTime("2012-04-15 15:23:34.123") works fine.
ParseExact should work for you, assuming your users have no way of editing that value on their own; in that case, you should use TryParseExact to unless you want the FormatException.
var toParse = "2012-04-15 15:23:34:123";
var parsed = DateTime.ParseExact(toParse, "yyyy-MM-dd HH:mm:ss:fff", null);
Assert.AreEqual(new DateTime(2012, 4, 15, 15, 23, 34, 123), parsed);
I have seen several answers to resolve the situation outlined in this question such as using DateTime.Parse, DateTime.ParseExact, or Convert.ToDateTime. I am trying to determine why the problem is seemlingly inconsistent. I built an application using the Microsoft Enterprise Library Software Factory with a SQL Server 2008 R2 backend and it has been in production for about 9 months now. It has at least 20 instances with the same code format that assign DateTime property values from C# to System.Data.DBType.DateTime parameters for stored procedures. 19 of the 20 code blocks work fine. For the 20th I had to add the .ToString() call as shown below to resolve the error mentioned in this question.
db.AddInParameter(command, "beginDT", DbType.DateTime, timeBlock.BeginDT.ToString());
So anyone have some insight on why would it work fine in 19 absolutely identical instances and not in the 20th? I am just trying to get more of an understanding of the inter-relationship of these objects so I can build solid code. I have since gone back to all other instances and added the .ToString() call. Haven't completed my regression testing though; so, I don't know if that was a mistake.

Date and time regular expression

I'm looking for a regular expression which matches the following datetime format:
dd-MMM-yyyy HH:mm:ss (15-Sep-2011 16:00:47)
Currently I only have the regex for date which looks something like this:
^(3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-](Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-]\d{4}$
Any ideas for the time part?
It's ok guys I found the solution. Submitting for anyone who wants to utilise it.
(3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-](Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-]\d{4}\s(20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d
Must it be a regex?
DateTime.TryParseExact will work much better.
DateTime myDate;
// dd-MMM-yyyy HH:mm:ss (15-Sep-2011 16:00:47)
if (DateTime.TryParseExact(dateAsString,
"dd-MMM-yyyy HH:mm:ss",
new CultureInfo("en-US"),
DateTimeStyles.None,
out myDate))
{ ... }
Err, it appears to me that the date bit is the hard one :-) But you can use the same methods for the time.
Assuming you have two fixed digits, you can use something like:
(([01][0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9]
The first bit is the slightly tricky bit since you want one of:
0 or 1 followed by a digit.
2 followed by 0 thru 3.
The minutes and seconds are both:
0 thru 5 followed by 0 thru 9.
If you want to allow single-digit hours, just replace [01] with [01]?.
You may also want to consider the possibility that people may enter nov or OcT as the month, rendering your regex less useful.
This could be solved with a case-insensitive version which would also reduce the size of the regex as well, requiring only one string per month.
As Joel suggested above that I should add my solution as an answer here.
So here it is:
(3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-](Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-]\d{4}\s(20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d
Do let me know if it works out.

Getting exception when using DateTime.Parse method

So, i have this string "Date: Mon Jan 03 2011 19:29:44 GMT+0200", and when i use DateTime.Parse(date).ToString(); i'm getting "String was not recognized as a valid DateTime."
If i remove the '+0200' part it works ok, but ofcourse it doesn't show the correct local time.
What's wrong with that?
From the documentation, it seems that DateTime.Parse() only understands:
The GMT designator, used alone, e.g. Mon, Jan 03 2011 17:29:44 GMT, or
A time zone offset specified without the GMT designator, e.g. Mon, Jan 03 2011 19:29:44+02:00.
You might want to convert your date string to the second form.
It just means that the time zone offset isn't an expected part of the default format strings.
If you know what format you're expecting, I suggest you call DateTime.ParseExact (or DateTime.TryParseExact), specifying the format(s) to try. Look at the documentation for custom date/time format strings for more details.
You have two mistakes.
First - don`t use Parse method. More correct is TryParse.
Second - you will have globalisation issues, when you use Parse or TryParse without arguments.
For example, see this code:
DateTime.Parse( "01.02.2011" ); In the USA it is 2nd of January. In the Germany it is 1st of February.
So, I recomment you to use formats from this article.

Categories

Resources