Parse C# String to Datetime

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.

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.

C# Parsing DateTime Unable to Convert String to DateTime

ParseExact() requires a perfect match. The MM/dd/yyyy format string would require 04/13/2018, but the value is 4/13/2018 12:00:00AM. You want M/d/yyyy hh:mm:sstt, and you should confirm day values don't have leading zeroes. There's also an overload that takes an array of format strings, if you can't trust the data source to be consistent.

Finally, per the comments, the compile-time type of Value is Object. But what about run-time? There's still a good chance the run-time type is already a DateTime value, and all you need to do is cast it. Because of internationalization/culture issues, converting to string and then re-parsing back to DateTime is suprisingly expensive. Avoiding those conversions will save the computer a ton of work, and really help performance.

How can I convert this 2012-08-16T19:20:30.456+08:00 string to DateTime using C#

The string in your example has an offset component so you can use DateTimeOffset:

var dateTimeOffset = DateTimeOffset.Parse("2012-08-16T19:20:30.456+08:00", CultureInfo.InvariantCulture);

From the linked docs:

The DateTimeOffset structure includes a DateTime value, together with
an Offset property that defines the difference between the current
DateTimeOffset instance's date and time and Coordinated Universal Time
(UTC).

C# parse DateTime String to time only

Your code is almost working, but ParseExact needs two additional arguments and ToString needs upper-case HH for 24h format:

var Time1 = DateTime.ParseExact("2021-06-14 19:27:14:979", "yyyy-MM-dd HH:mm:ss:fff", null, DateTimeStyles.None);
var Time2 = Time1.ToString("HH:mm:ss:fff");

Read: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#uppercase-hour-h-format-specifier

Instead of passing null as format provider(means current culture) you might want to pass a specifc CultureInfo, for example CultureInfo.CreateSpecificCulture("en-US").

Difficulty parsing string to DateTime

DateTime.Parse uses standard date and time formats of your CurrentCulture settings by default. Looks like dd.mm.yyyy is not one of them.

You can use DateTime.ParseExact or DateTime.TryParseExact methods to specifiy your format exactly.

By the way, I strongly suspect you mean MM (for months) instead of mm (for minutes).

DateTime userBirthday = DateTime.ParseExact(Console.ReadLine(), 
"dd.MM.yyyy",
CultureInfo.InvariantCulture);

By the way, calculating age is difficult in programming since it depends on where you were born and where you are right now.

Check this: Calculate age in C#



Related Topics



Leave a reply



Submit