Date and time regular expression - c#

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.

Related

How do I format a single digit month in C# date formatting?

In C#, if I run this code, it prints out 05:
Console.WriteLine(DateTime.Now.ToString("MM"));
However, if I run this code, it prints out May 16:
Console.WriteLine(DateTime.Now.ToString("M"));
I'm looking for a date format that will print out 5. How do I format a single digit month? To be clear, it would be 1 digit for months 1 to 9, and 2 digits for months 10 to 12.
“%M" should work. See custom format strings
Some explanation:
The "M" can be part of a custom format string, where it means a "month number" in one or two digits
But on itself it can also be a standard format string meaning a "month day pattern" - as the OP found out.
To resolve this ambiguity you can add a space, which makes it a custom format string, but also adds a space to the resulting value. Or you can add a %.
Right now (May) a DateTime.Now.ToString("%M") results in "5".
Microsoft has some excellent documentation regarding how to format DateTime as string values over at https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
The parameter you're looking for is M which would make the method call DateTime.Now.ToString("M");.
Update:
However, as pointed ut by Hans Kesting, this could give unexpected results in some situations which can be avoided by using a % in combination with the M as described at https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#UsingSingleSpecifiers

C# Converting to date from inconsistent string

I'm trying to parse a file where I get my dates as string like those:
5/18/2020 8:38:32 AM
6/8/2021 10:11:42 PM
11/24/2021 9:21:54 AM
----
I tried to use a DateTime.TryParse on my string and test the "---" case in a if statement which work but it succeed to convert only the 6/8/2021 12:41:56 PM.
I tried to use TryParseExact and specify a date format but it seem that I should make a case months with one and two digits and same the days.
I guess there is something I'm not seeing or don't know.
Thanks for you help.
It is because you are probably on a culture other than en-US which those dates are formatted in. Use IFormatProvider parameter. ie:
void Main()
{
var dates = #"5/18/2020 8:38:32 AM
6/8/2021 10:11:42 PM
11/24/2021 9:21:54 AM
----";
foreach (string s in dates.Split('\n'))
{
if (DateTime.TryParse(s, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime d))
{
Console.WriteLine(d);
}
}
}
Here is the .Net fiddle link.
EDIT: Note that the version on .Net fiddle is slightly different because of the older C# version there.
Without the exact details, I have to guess:
If he only can translate the 6/8 date, you may have the wrong locale settings (you have something like MM/dd/yyyy .... but this works only for the 8th of june, what you might get wrong with 6th of august)
If you use ParseExact, you can also provide a list of valid format strings.
EDIT
Cetins answer is correct. Additionally, the title of the post is a bit confusing, because the datetime string IS consistent (in the 'en-US' local settings)
#Cetin Basoz You are right, it was indeed a culture problem. Thank you!
#nabuchodonossor You are right about the datetime string ("----" apart) being consistent. What I wanted to say was that there is no every time two digits for the days or months which would not happen if the dates were something like 05/18/2020 and 06/08/2021. Sorry, I have a hard time being precise.

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.

Regular expression to validate date - C#

I am using a calenderExtender control to get a date from user. The text box can be edit manually by the user. I am using a RegularExpressionValidator to validate Input date. The input format i need is
MMM dd, yyyy
Now i am using a regular expression shown below to validate date
((Jan)|(Feb)|(Mar)|(Apr)|(May)|(Jun)|(Jul)|(Aug)|(Sep)|(Oct)|(Nov)|(Dec)){1}\s?\d{1,2},\s?\d{4}
It works fine. But it do not check the input date is less than 28,30 or 31 based on month . example :the month December have 31 days. If the user entered greater than 31 ,the expression must caught that.
Any ideas to achieve this using regular exptression??
The validation that you want to do (excluding invalid date ranges based on month) is really unsuited for a regular expression. You should parse the month, date, and year, and then do your validation based on the parsed values. Trying to do it via a regex will be painful and difficult to maintain.
Alternately, have you considered just using DateTime.Parse?
If you think that's bad, just wait till you try supporting leap years. Yep, as is usually the case with "how do I do (insert difficult task) with regex?" questions, the best approach is to just avoid regular expressions entirely. Can you use a RangeValidator instead? Otherwise, as JSBangs noted, you could use a custom validator with DateTime's parsing methods.

How to Convert date into MM/DD/YY format in C#

In My Asp.net webpage I need to display today's date into one of the textbox , so in my form load I wrote the following code
textbox1.text = System.DateTime.Today.ToShortDateString();
this line is giving me date like 1/7/09 but I want date like 01/07/09 , Is there anyway I can conver this date into mm/dd/yy format in C#?
DateTime.Today.ToString("MM/dd/yy")
Look at the docs for custom date and time format strings for more info.
(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)
DateTime.Today.ToString("MM/dd/yy")
Look at the docs for custom date and time format strings for more info.
(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)
Others cultures really are a problem. For example, that code in portugues returns someting like 01-01-01 instead of 01/01/01. I also don't undestand why...
To resolve that problem i do someting like this:
IFormatProvider yyyymmddFormat = new System.Globalization.CultureInfo(String.Empty, false);
return date.ToString("MM/dd/yy", yyyymmddFormat);
Have you tried the following?:
textbox1.text = System.DateTime.Today.ToString("MM/dd/yy");
Be aware that 2 digit years could be bad in the future...
Look into using the ToString() method with a specified format.
See, here you can get only date by passing a format string.
You can get a different date format as per your requirement as given below for current date:
DateTime.Now.ToString("M/d/yyyy");
Result : "9/1/2016"
DateTime.Now.ToString("M-d-yyyy");
Result : "9-1-2016"
DateTime.Now.ToString("yyyy-MM-dd");
Result : "2016-09-01"
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
Result : "2016-09-01 09:20:10"
For more details take a look at MSDN reference for Custom Date and Time Format Strings

Categories

Resources