Parse String to Datetime in C#

Parse string to DateTime in C#

DateTime.Parse() will try figure out the format of the given date, and it usually does a good job. If you can guarantee dates will always be in a given format then you can use ParseExact():

string s = "2011-03-21 13:26";

DateTime dt =
DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

(But note that it is usually safer to use one of the TryParse methods in case a date is not in the expected format)

Make sure to check Custom Date and Time Format Strings when constructing format string, especially pay attention to number of letters and case (i.e. "MM" and "mm" mean very different things).

Another useful resource for C# format strings is String Formatting in C#

How to parse string to DateTime with a. m. or p. m. format (not AM/PM)?

This is what the tt custom format specifier are for.

var date = "6/01/2018  12:00:03 am";
var x = DateTime.ParseExact(date, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

But remember, this tt specifier does not parse a. m. or a.m. strings. If your strings have those, you have to manipulate your strings like removing dots and/or spaces between a and m etc.. It also parse AM and PM as well.

Converting dd/mm/yyyy formatted string to Datetime

You need to use DateTime.ParseExact with format "dd/MM/yyyy"

DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Its safer if you use d/M/yyyy for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.


Your date format day/Month/Year might be an acceptable date format for some cultures. For example for Canadian Culture en-CA DateTime.Parse would work like:

DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));

Or

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture

Both the above lines would work because the the string's format is acceptable for en-CA culture. Since you are not supplying any culture to your DateTime.Parse call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.


Another method for parsing is using DateTime.TryParseExact

DateTime dt;
if (DateTime.TryParseExact("24/01/2013",
"d/M/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//valid date
}
else
{
//invalid date
}

The TryParse group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool value indicating success or failure in parsing.

Notice that I have used single d and M for day and month respectively. Single d and M works for both single/double digits day and month. So for the format d/M/yyyy valid values could be:

  • "24/01/2013"
  • "24/1/2013"
  • "4/12/2013" //4 December 2013
  • "04/12/2013"

For further reading you should see: Custom Date and Time Format Strings

c# - Convert string to datetime with DateTime.ParseExact

DateTime.ParseExact has an overload that takes a string array of possible formats to use for parsing. Use that overload and reduce your code to a line or two.

string[] formats = new string[] {"dd-MM-yyyy HH:mm:ss:fff",
"dd-MM-yyyy H:mm:ss:fff",
"dd-MM-yyyy HH:mm:ss:f",
"dd-MM-yyyy HH:mm:ss",
....};

finished = DateTime.ParseExact(a, formats, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);

If you don't know all the possible formats you could also read them from an external file to avoid recompiling your application if a new format pops up

Also, as said in the comments below, I prefer to use DateTime.TryParseExact to have more control on the outcome of the parsing and avoid a costly exception handling in case of a format not recognized.

Parse string to DateTime in C# mimicking behavior of SQL Server CAST/CONVERT

Update: @jeroen-mostert's comment about using SqlDateTime.Parse is probably a better answer than what what we wound up going with.

Original answer:

In case it helps anyone in the future, the answer wound up being to use DateTime.TryParse() and, if that failed, calling DateTime.TryParseExact() with the special formats not already supported by TryParse().

From glancing over the source code it seems that Parse/TryParse is more lenient about things like separators, such that it works even with similar formats that are not shown when enumerating dateTimeFormatInfo.GetAllDateTimePatterns(). I believe that explains why TryParseExact didn't seem to work with formats that TryParse supported, even when TryParseExact was using all the DateTime patterns provided by the DateTimeFormatInfo object.

I did also validate format support against the listed Date and Time Styles in Microsoft's docs. This solution doesn't support 100% of them, though. That is by design since some combinations can be non-deterministic, and we are thankfully confined to a specific culture.

Not a perfect solution, as pointed out in the comments, but it did the trick here.

Convert time string to DateTime in c#

This is as simple as parsing a DateTime with an exact format.

Achievable with

var dateStr = "14:00";
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);

The DateTime.ParseExact() (msdn link) method simply allows you to pass the format string you wish as your parse string to return the DateTime struct. Now the Date porition of this string will be defaulted to todays date when no date part is provided.

To answer the second part

How can I get a DateTime object with current date as the date, unless
current time already 14:00:01, then the date should be the next day.

This is also simple, as we know that the DateTime.ParseExact will return todays date (as we havevnt supplied a date part) we can compare our Parsed date to DateTime.Now. If DateTime.Now is greater than our parsed date we add 1 day to our parsed date.

var dateStr = "14:00";

var now = DateTime.Now;
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);

if (now > dateTime)
dateTime = dateTime.AddDays(1);

How to convert string with a T and Z to DateTime

You could try something like this:

var dateString = "20150521T205510Z";

var date = DateTime.ParseExact(dateString,
"yyyyMMdd'T'HHmmss'Z'",
CultureInfo.InvariantCulture);

I referenced the answer from: DateTime.Parse("2012-09-30T23:00:00.0000000Z") always converts to DateTimeKind.Local



Related Topics



Leave a reply



Submit