Parsing a Date Like "Wednesday 13th January 2010" with .NET - c#

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);

Related

Convert string with long month name to DateTime

I have this string July 1, 2021 9:10 AM and I'm trying to parse it into a DateTime variable.
This isn't working for me. ST is a variable that has the string representation of the date and time.
var Event = DateTime.ParseExact(ST, "MMMM dd, yyyy h:mm tt", CultureInfo.InvariantCulture);
You are using the wrong day format. For a month day without a leading zero, you should use the following:
var Event = DateTime.ParseExact(ST, "MMMM d, yyyy h:mm tt", CultureInfo.InvariantCulture);

Convert written date in c# .Net

I get from an web service a date which is written like that :
"Tuesday, November 12, 2013 8:18:14 AM PST"
or
"Tuesday, November 12, 2013 10:36:03 AM PST"
or
"Wednesday, November 13, 2013 5:15:58 AM PST"
...
This date is stored inside an Array and I would like to sort it. But It does not work properly. So I would like to store this written date in a DateTime or another format supported by the language. Than sort it again. I could be also easier to get only days and hours from a DateTime than using a strstr or something like that.
Is it possible (and how) to convert this written date into a DateTime please ?
PS: I already tried using Convert.DateTime("Wednesday, November 13, 2013 5:15:58 AM PST"). But It didn't work.
Thanks
You need to parse it with format "dddd, MMMM d, yyyy h:m:ss tt 'PST'"
string str = "Wednesday, November 13, 2013 5:15:58 AM PST";
DateTime dt = DateTime.ParseExact(str,
"dddd, MMMM d, yyyy h:m:ss tt 'PST'",
CultureInfo.InvariantCulture);
I have used single d, h and m, for day, hour and month since they will accept both single digit and double digits values.
Becuase Convert.DateTime uses current culture information.
The value argument must contain the representation of a date and time
in one of the formats described in the DateTimeFormatInfo topic.
You can use DateTime.ParseExact method with custom datetime format instead.
string s = "Wednesday, November 13, 2013 5:15:58 AM PST";
DateTime dt = DateTime.ParseExact(s,
"dddd, MMMM d, yyyy h:mm:ss tt 'PST'",
CultureInfo.InvariantCulture);
Console.WriteLine(dt);
Output will be;
11/13/2013 5:15:58 AM
Here a demonstration.
For more informations, take a look at;
Custom Date and Time Format Strings
If the date will always end with a 3 letter timezone abbreviation the following will work:
string str = "Wednesday, November 13, 2013 5:15:58 AM PST";
DateTime date = DateTime.Parse(str.Substring(0, str.Length - 4));

Datetime.ParseExact is not working

This may be one of those stupid, I missed something errors but here it goes.
I have a date time in string format (no trailing or leading whitespaces)
Sun 27 Apr 2013 7:30pm
I use this code to turn it into a DateTime variable but it always returns false
DateTime date;
bool dateParsed = false;
CultureInfo provider = CultureInfo.InvariantCulture;
dateParsed = DateTime.TryParseExact(when, "ddd d MMM yyyy h:mmtt", provider, DateTimeStyles.AssumeLocal, out date);
Hopefully someone can quickly tell me what I am doing wrong here.
Because April 27th, 2013 fell on a Saturday, not on a Sunday. If you try to parse
Sat 27 Apr 2013 7:30pm
It should work. You can see that by printing out the date using the same format, and comparing it with what you're trying to parse.
bool dateParsed = false;
DateTime date;
CultureInfo provider = CultureInfo.InvariantCulture;
string when = "Sat 27 Apr 2013 7:30pm";
dateParsed = DateTime.TryParseExact(when, "ddd d MMM yyyy h:mmtt", provider, DateTimeStyles.AssumeLocal, out date);
Console.WriteLine(date);
date = new DateTime(2013, 4, 27, 19, 30, 00, DateTimeKind.Local);
Console.WriteLine(date.ToString("ddd d MMM yyyy h:mmtt", provider));
Change your code to use ParseExact instead. It gives you the exact problem by crashing with an exception:
String was not recognized as a valid DateTime because the day of week was incorrect.
April 27 2013 is a Saturday, not a Sunday.
The problem is your date, which is invalid. Change it like
Sat 27 Apr 2013 7:30pm
Check this screenshot,
Here is your code:
DateTime date;
bool dateParsed = false;
CultureInfo provider = CultureInfo.InvariantCulture;
string when = "Sat 27 Apr 2013 7:30pm";
dateParsed = DateTime.TryParseExact(when, "ddd d MMM yyyy h:mmtt", provider, DateTimeStyles.AssumeLocal, out date);

Error : String was not recognized as a valid DateTime while converting to date format in c#

Here is the date time format i'm trying to format.I'm getting this date format from twitter apis
string date = "Thu Jul 18 17:39:53 +0000 2013"
i tried
Convert.ToDateTime(date).ToString("dd/MM/yyyy")
But it says String was not recognized as a valid DateTime.
This works:
DateTime.ParseExact(dtStr, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture)
ParseExact and TryParseExact allows to use a custom format string. ddd is the abbreviated day name, MMM the abbreviated month name, dd the day number, HH hours in 24h clock format, mm minutes, ss seconds, zzzz the time-zone and yyyy the years.
I have used CultureInfo.InvariantCulture to specify that the current culture is not used but InvariantCulture which is similar to "en-US".
Demo
works but after getting date from your line of code i tried to do
date.ToString("dd/mm/yyyy") but get the string as 12-12-2013, no
slashes
/ is a replacement character for your current culture's date-separator which is obviously -. So also use CultureInfo.InvariantCulture to specify that the separator should be used without using your current culture:
string result = dateTime.ToString("dd/mm/yyyy", CultureInfo.InvariantCulture);
See: The "/" Custom Format Specifier
Try this
DateTime.ParseExact(YourDate, "ddd MMM dd HH:mm:ss KKKK yyyy", CultureInfo.InvariantCulture)
Its better to use Invariant culture than Current culture
You are trying to convert a non-standard format, so use this:
string dateStr = "Thu Jul 18 17:39:53 +0000 2013";
DateTime date = DateTime.ParseExact(dateStr, "ddd MMM dd h:mm:ss KKKK yyyy", System.Globalization.CultureInfo.InvariantCulture);
Or build the correct format for your input.
How about like;
string date = "Thu Jul 18 17:39:53 +0000 2013";
DateTime dt = DateTime.ParseExact(date, "ddd MMM dd HH:mm:ss KKKK yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(dt);
Output will be;
18.07.2013 20:39:53
K for time zone information in here.
Check out for more information;
Custom Date and Time Format Strings
Your date string needs to be this:
Thu Jul 18 2013 17:39:53 +0000
Whatever is producing your string needs to have the year value after the month and day and before the time, like above.
string date = "Thu Jul 18 2013 17:39:53 +0000";
var theDate = Convert.ToDateTime(date);
Note: This will produce a valid .NET DateTime object.
UPDATE:
If you cannot change the string produced, then use the ParseExact method with a custom format, like this:
string date = "Thu Jul 18 17:39:53 +0000 2013";
var theDate = DateTime.ParseExact(date, "ddd MMM dd H:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
Try using DateTime.ParseExact.
string date = "Thu Jul 18 17:39:53 +0000 2013"
DateTime date = DateTime.ParseExact(date, "dd/MM/yyyy", null);
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);

Parse datetime string in the format "Nov. 7, 2012, 9:02 p.m."

How can I parse a date string in the format "Nov. 7, 2012, 9:02 p.m."
I think I'm close. Have tried:
string line = "Nov. 7, 2012, 9:02 p.m.";
string format = "MMM. dd, yyyy, hh:mm p.m."; ;
DateTime result = DateTime.ParseExact(line, format, null);
This will work.
string format = string.Format("{0:MMM. dd, yyyy, hh:mm tt}", DateTime.Now);
Console.WriteLine(format);
This will print the result in your expected format ( Nov. 7, 2012, 9:02 PM)
string format = "MMMM. dd, yyyy, hh:mm p.m.";
your taking the full month with 4 M's
Try
string format = "MMM. dd, yyyy, hh:mm p.m.";
to get the short month ie November -> Nov
Here's the reference guide: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Use a singleh instead of hh. Also , t.'m'. might match your a.m./p.m. depending on if it's case sensitive.

Categories

Resources