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 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).
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
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);
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.
Converting a UK formatted string DateTime ( dd/MM/yyyy ) to a valid DateTime where the culture may change
Method 1 - You can use ParseExact
by giving the input format
string inputdate = "01/12/2019";
var date = DateTime.ParseExact(inputdate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Method 2 - If you have many input formats, you can use TryParseExact
string inputdate = "01/12/2019";
DateTime dateTime = ParseDate(inputdate )
private static DateTime ParseDate(string providedDate)
{
DateTime validDate;
string[] formats = { "dd/MM/yyyy", "dd.MM.yyyy" };
var dateFormatIsValid = DateTime.TryParseExact(
providedDate,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out validDate);
return dateFormatIsValid ? validDate : DateTime.MinValue;
}
Convert string to DateTime in c#
Try this:
DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
If the string may not be in the correct format (and you wish to avoid an exception) you can use the DateTime.TryParseExact
method like this:
DateTime dateTime;
DateTime.TryParseExact(str, "yyyyMMddHHmmss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
C# to Convert String to DateTime
Try DateTime.ParseExact
instead.
Example:
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);
More examples are available at http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
Related Topics
How to Add an Attribute to a Property at Runtime
How to Convert This Foreach Code to Parallel.Foreach
How to Parse (Big) Xml in C# Code
Wpf Webbrowser Control - How to Suppress Script Errors
Writing Large Number of Records (Bulk Insert) to Access in .Net/C#
New Keyword in Method Signature
Interprocess Communication for Windows in C# (.Net 2.0)
Calling a Method Every X Minutes
How to Read the Color of a Screen Pixel
C# Open a New Form Then Close the Current Form
How to Make an Event in the Usercontrol and Have It Handled in the Main Form
Http Error 500.30 - Ancm In-Process Start Failure
Method Cannot Be Translated into a Store Expression
Testing If Object Is of Generic Type in C#
How to Send Emails Through Ssl Smtp with the .Net Framework
How to Pass Ienumerable List to Controller in MVC Including Checkbox State