Parsing Dates and Times in .NET
Parsing dates and times using DateTime.Parse and DateTime.ParseExact is simple enough once you know how they work.
It’s simple if you know the format of the string you’re getting and it exactly matches one of the built-in formats, or if you’re willing to let the framework do it’s best to parse the string and you’re ok with it failing otherwise, but if you need to parse specific formats, you’ll need to build your own format specifiers.
There are two ways of parsing date strings: Parse and ParseExact
DateTime.Parse() is the simplest.It tries to figure out the format of the date, and usually does a pretty good job. Here are some examples that work for me, with the result of a DateTime.ToString() on the parsed date:
|
String to parse |
Resulting DateTime.ToString |
|
01-Jan-2005 |
1/1/2005 12:00:00 AM |
|
01-Jan-2005 12:34 PM |
1/1/2005 12:34:00 PM |
|
1/1/05 1:3 |
1/1/2004 1:03:00 AM |
|
1 march, 2005 1 am |
3/1/2005 1:00:00 AM |
|
1995-02-04 |
2/4/1995 12:00:00 AM |
|
February 3 |
2/3/2005 12:00:00 AM |
|
10:30 |
2/15/2005 10:30:00 AM |
|
10 am |
2/15/2005 10:00:00 AM |
These all did what we expected. DateTime.Parse() is probably the best function to use if the user is typing in a date, and you want it parsed so you can work with it.
If you’re receiving your date strings from data (network, etc), and they’re in a specific format, check this table to see if there’s a predefined format string for your format:
|
Standard |
Format |
Example Date |
||
|
RFC1123 |
r |
Sun, 06 Nov 1994 08:49:37 GMT |
||
|
ISO 8601 (almost) |
s |
1993-02-14T13:10:30 |
||
|
Universal Sortable |
u |
|
1 2 | // Parse an RFC1123 date<br /> DateTime dt = DateTime.ParseExact(dateString, "r"); |
There are other strings you can pass to ParseExact, but they’re culture-specific, so generally not all that useful.
In many cases, you have a date string in a specific format,which doesn’t just work with DateTime.Parse. One example is this one, which is allowed by the the ISO 8601 standard, but not parsed by ParseExact when you specify the ‘s’ specifier:
19930214T131030
To parse this, you need to build a string that specifies the format you’re expecting, using characters from this table:
|
Format specifier |
Description |
|
d, dd, ddd, dddd |
Current day of the month d, dd=numeric, ddd=abbreviation (ie, ‘Wed’), dddd=spelled out. |
|
f, ff, fff, ffff, fffff, … |
Fractions of a second, varying numbers of digits |
|
h, hh |
Hours, 12 hour format. |
|
H, HH |
Hours, 24 hour format |
|
m, mm |
Minutes |
|
M, MM, MMM, MMMM |
Month. MM = 2 digit, MMM = abbreviation (ie, ‘Jan’), MMMM=Spelled out. |
|
s, ss |
Seconds |
|
t, tt |
AM/PM indicator. |
|
y, yy, yyyy |
Year |
|
z, zz, zzz |
Time zone offset from GMT. |
|
: |
Time separator. |
|
/ |
Date separator. |
|
Any other character |
Other characters are matched as literals. |
So to parse our sample date, you’d use this string:
1 2 | // Parse an RFC1123 date<br /> DateTime dt = DateTime.ParseExact("19930214T131030", "yyyyMMddTHHmmss"); |
The help covers this stuff fairly well, once you find the documentation. Look for ‘Standard DateTime Format Strings‘ and ‘Custom DateTime Format Strings‘ if you haven’t found what you need here (and let me know, so I can add it).
If you’re receiving strings in a number of formats and you’re not really sure what you’re going to get (like, say, if you’re writing a program that does something with RSS feed data), it’s convenient that you can pass in multiple format specifiers to ParseExact. For example:
1 2 | string[] formats = new string[] { "r", "s", "u", "yyyyMMddTHHmmss" };<br /> DateTime dt = DateTime.ParseExact(dateString, formats,<br /> CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); |
This is most likely to get you a date you can use.
November 11th, 2005 at 7:19 pm
The first examples are easy, but be careful if you use something other than CultureInfo.InvariantCulture or a specific format string. Culture data may be different between the source and target machines in a networked environment. Also users can customize their data, such as by creating a custom replacement locale. Lastly Microsoft can changes the format data for specific cultures in new versions of .Net. This can happen if the original data was wrong, or if cultural preferences shifted or for GPS issues.
March 17th, 2006 at 9:03 am
Thanks mate, been looking around for this everywhere…couldn’t get 20060317065348 to work with ParseExact.
Cheers
April 3rd, 2006 at 4:36 pm
Thanks for the post. One of the very few that I found on this method
April 5th, 2006 at 3:11 am
Exactly what i needed. Thanks!
April 10th, 2006 at 12:09 pm
DateTime.Parse(“19930214T131030″) works fine.
April 25th, 2006 at 3:22 pm
Thanks. I had the same problem with the yyyy-MM-ddTHH:mm:ss:fff format we are using.
This was very helpful.
June 8th, 2006 at 7:24 am
I’m having a heck of a time with ISO like datetime format that we use and the ParseExact() method and fractions of a second. Below are two datetimes that I try to process with it, both seemingly valid datetimes. Do you or anyone anyone know what the first one does not work but the second one does?
string dateTime = null;
dateTime = “2006-06-07T15:24:24.330″; // ParseExact Result = String was not recognized as a valid DateTime.
//dateTime = “2006-09-29T13:24:03:000″; // ParseExact Resul = 9/29/2006 1:24:03 PM
DateTime parsedDate = DateTime.ParseExact(
dateTime, “yyyy-MM-ddTHH:mm:ss:ff”, CultureInfo.InvariantCulture);
June 29th, 2006 at 10:46 pm
Amazing how the documentation doesn’t make it this easy to understand, for something you ought to look up quite often.
July 26th, 2006 at 9:19 pm
To Keith,
The first DateTime instance use “.” as a delimiter between seconds and milliseconds where as the second instance uses “:”.
If you want to include both formats, then you can do
string[] formats = new string[] { “yyyy-MM-ddTHH:mm:ss:fff”, “yyyy-MM-ddTHH:mm:ss.fff” };
DateTime parsedDate = DateTime.ParseExact(dateTime, formats, CultureInfo.InvariantCulture);
Hope this helps,
sonyoak
February 27th, 2007 at 6:38 am
I have a date like “Wed Feb 21 21:33:16 UTC+0100 2007″. I tryed to use a string like “ddd MMM dd HH:mm:ss” but it doesn’t work. Any ideas?
Thanks!
Niko
March 30th, 2007 at 9:18 am
Is there any way to know the format of what the user put in or even what the user actualy specified.
so if the user put: Feb 2007
then I would know “MMM YYYY”
or if I could even know that they put in a year and a month. As far as I can see The result for “Jan 2007″ and “2007″ is the same and I would like to know if they put in a month.
June 19th, 2007 at 6:30 pm
Great tutorial!!!
For those dumb c# newbies like myself. CultureInfo is part of System.Globalization.
using System.Globilization;
DateTime UTCtime = DateTime.ParseExact(“235959.99″,”HHmmss.ff”,CultureInfo.InvariantCulture);
July 6th, 2007 at 4:31 pm
> I have a date like “Wed Feb 21 21:33:16 UTC+0100 2007″. I tryed to use a string like “ddd MMM dd
> HH:mm:ss” but it doesn’t work. Any ideas?
> Thanks!
> Niko
Try this:
DateTime.ParseExact(dateString, “ddd MMM dd HH:mm:ss ‘UTC’zzzz yyyy”, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
August 29th, 2007 at 3:00 pm
I have a date which takes in a format of xsd:dateTime:
I got the solution for it. To construct the dateString, I was using the following format:
string dateString = DateTime.Now.ToString(“yyyy-mm-ddThh:mm:ss”);
This was erroring out on the DateTime.ParseExact line. I changed the dateString construct to:
string dateString = DateTime.Now.ToString(“s”);
It converts to the same string except the time format is for 24 hours. It works, now.
Thanks,
Sameer.
November 18th, 2007 at 12:54 pm
[...] Blog post from SteveX on using DateTime.ParseExact [...]
January 16th, 2008 at 11:46 pm
Does anyone know where I can find documentation on how parseexact handles 2 digit years?
November 7th, 2008 at 3:05 pm
I just love this page. It’s so much more concise and useful than the MSDN documentation.
January 30th, 2009 at 11:48 pm
Everyone can write but a few can make things crystal clear. You are one among them.
Very nice
July 17th, 2009 at 10:50 am
I would like to take parse a DateTime and return only the time , is there a way to manage that.Thanks
March 25th, 2010 at 10:23 am
Good to read this too: http://stackoverflow.com/questions/266448/format-rss-pubdate-as-net-datetime/2516798#2516798