Parsing a complicated string as DateTime - c#

Can someone tell me how should I approach converting the following format to a proper DateTime object?
11:50:46 AM on Wednesday, October 19, 2011

string s = "11:50:46 AM on Wednesday, October 19, 2011";
DateTime dateTime = DateTime.ParseExact(s,
"hh:mm:ss tt on dddd, MMMM dd, yyyy", CultureInfo.InvariantCulture);

Related

DateTime.ToLongDateString with different culture

How can I convert a date(DateTime) to a string in a long format with the culture I need?
But the method(DateTime.ToLongDateString()) of converting date to long format string does not accept culture.
Long date string: "Wednesday, May 16, 2001"
In short, you can do this:
DateTime date = DateTime.Now;
date.ToString(CultureInfo.CreateSpecificCulture("en-US"));
ToLongDateString is using the format info's LongDatePattern, which is "dddd, MMMM d, yyyy".
So you can use:
date.ToString("dddd, MMMM d, yyyy", CultureInfo.CreateSpecificCulture("en-US"));
Or simpler, use the long date ("D") format specifier "D":
date.ToString("D", CultureInfo.CreateSpecificCulture("en-US"));
Result: Thursday, October 27, 2022

Convert string to DateTIme from specific format

I have the following string: Monday, April 20, 2020 at 9:11 AM,
How can I convert it into DateTime object?
What I'm trying:
DateTime myDate = DateTime.ParseExact(
"Monday, April 20, 2020 at 9:11 AM",
"yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
But as except yyyy-MM-dd HH:mm:ss,fff not working to this format.
Any suggestions?
Try it here: https://dotnetfiddle.net/uBnqhz
DateTime myDate = DateTime.ParseExact("Monday, April 20, 2020 at 9:20 AM",
"dddd, MMMM dd, yyyy 'at' h:m tt",
System.Globalization.CultureInfo.InvariantCulture);
Please try to use the following format string: "dddd, MMMM d, yyyy 'at' h:mm tt".
Also, as suggested in the comments, documentation is your friend.
Here you go
DateTime myDate = DateTime.ParseExact("Monday, April 20, 2020 at 9:11 AM", "dddd, MMMM dd, yyyy 'at' h:mm tt", new System.Globalization.CultureInfo("en"));

Convert DateTime Format to Tuesday, 03 May 2016

In my asp.net page i want to display date in this format Tuesday, 03 May 2016 but when i retrieve data from sql server its showing 3/05/2016 12:00:00 AM
How to convert 3/05/2016 12:00:00 AM - to - Tuesday, 03 May 2016 in C# Code Behind File
Actually this is my code :
string strAccountCreatedDate = ds.Table[0].Rows[0]["AccountCreatedDate"].ToString();
strAccountCreatedDate = 3/05/2016 12:00:00 AM
Now i want to Convert strAccountCreatedDate Format to Tuesday, 03 May 2016 in through C# Coding
Try this
DateTime dt = DateTime.ParseExact("03/05/2016 12:00:00 AM", "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
string newdate = dt.ToString("dddd, dd MMM yyyy");
Console.WriteLine(newdate);
You should go through this link for conversion in any date format
DateTime dt = DateTime.Now;
string date = String.Format("{0:dddd,dd MMM yyyy}", dt);
Response.Write(date);
Try this :-
string strAccountCreatedDate = ds.Table[0].Rows[0]["AccountCreatedDate"].ToString();
DateTime dt = Convert.ToDateTime(strAccountCreatedDate);
string Formatteddate = dt.ToString("dddd, dd MMM yyyy");

Is there a way in .net razor to convert a String with unusual format into datetime [duplicate]

How can I convert the following strings to a System.DateTime object?
Wednesday 13th January 2010
Thursday 21st January 2010
Wednesday 3rd February 2010
Normally something like the following would do it
DateTime dt;
DateTime.TryParseExact(value, "dddd d MMMM yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt);
but this doesn't work because of the 'th', 'st' or 'rd' in the string
Update
It appears that DateTime doesn't support formatting the 'th', 'st', 'rd' etc so they need to be stripped before parsing. Rubens Farias provides a nice regular expression below.
What about strip them?
string value = "Wednesday 13th January 2010";
DateTime dt;
DateTime.TryParseExact(
Regex.Replace(value, #"(\w+ \d+)\w+ (\w+ \d+)", "$1 $2"),
"dddd d MMMM yyyy",
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None, out dt);
Another approach.
string sDate = "Wednesday 13th January 2010";
string[] sFields = sDate.Split (' ');
string day = sFields[1].Substring (0, (sFields[1].Length - 2));
DateTime date = new DateTime (sFields[3], sFields[2], day);
Another alternative using escape characters for handling (st, nd, rd, and th) without stripping them before the call of DateTime.TryParseExact
string dtstr = "Saturday 23rd January 2016";
DateTime dt;
string[] formats = new string[] {
"dddd d\\s\\t MMMM yyyy", "dddd d\\n\\d MMMM yyyy",
"dddd d\\r\\d MMMM yyyy", "dddd d\\t\\h MMMM yyyy" };
bool result = DateTime.TryParseExact(dtstr, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Where does "th", "st","nd" or "rd" appear below?
monday
tuesday
wednesday
thursday
friday
saturday
sunday
january
february
march
april
may
june
july
august
september
october
november
december
However you know those 4 will always be followed by a space. So unless I've missed something, a simple
value = value.Replace("August","Augus").Replace("nd ","").Replace("st ","").Replace("nd ","").Replace("rd ","").Replace("Augus","August");
DateTime dt;
DateTime.TryParseExact(value,"DDDD dd MMMM yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt);
No credit to me but this looks interesting for general DataTime parsing: http://www.codeproject.com/KB/datetime/date_time_parser_cs.aspx?msg=3299749
I remembered this post on using MGrammar to parse a lot of different ways to express dates and times. It doesn't exactly answer your question, but it might serve as a useful base depending on what your ultimate goal is.
Expanding on Kenny's approach, I added some code to pass integers to the DateTime variable...
string sDate = "Wednesday 13th January 2010";
string[] dateSplit = sDate.Split (' ');
string day = dateSplit[1].Substring(0, dateSplit[1].Length - 2);
int monthInDigit = DateTime.ParseExact(dateSplit[3], "MMMM", CultureInfo.InvariantCulture).Month;
DateTime date = new DateTime(Convert.ToInt16(year), monthInDigit, day);

Format String to Datetime with Timezone

I have a string s = "May 16, 2010 7:20:12 AM CDT that i want to convert into a DateTime object. In the code below i get a Date format cannot be converted error when attempting to parse the text with a known format.
timeStamp = matches[0].Groups[1].Value;
dt = DateTime.ParseExact(timeStamp, "MMM dd, yyyy H:mm:ss tt", null);
The timezone comes in as CDT UTC... and i think is whats causing the problem or my format?
Central Daylight Time
Try this:
string dts = "May 16, 2010 7:20:12 AM CDT";
DateTime dt =
DateTime.ParseExact(dts.Replace("CDT", "-05:00"), "MMM dd, yyyy H:mm:ss tt zzz", null);
EDIT:
For daylight savings time please consider DateTime.IsDaylightSavingTime and TimeZone.CurrentTimeZone
Custom Date and Time Format Strings
Make sure the DateTime is unambiguously DateTimeKind.Utc. Avoid "GMT", it is ambiguous for daylight saving.
var dt = new DateTime(2010, 1, 1, 1, 1, 1, DateTimeKind.Utc);
string s = dt.ToLocalTime().ToString("MMM dd, yyyy HH:mm:ss tt \"GMT\"zzz");
it's gives output : Dec 31, 2010 19:01:01 pm GMT-06:00
For more detail refer this Link
I convert my date string with timezone "Thu, 22 Sep 2022 06:38:58 +0200" using "ddd, dd MMM yyyy HH:mm:ss zzz":
var dateString = "Thu, 22 Sep 2022 06:38:58 +0200";
string[] acceptedDateFormats = { "ddd, dd MMM yyyy HH:mm:ss zzz" };
var dateParsed = DateTime.TryParseExact(dateString, acceptedDateFormats,
CultureInfo.InvariantCulture, DateTimeStyles.None, out var date);

Categories