How do you convert a string such as 2009-05-08 14:40:52,531
into a DateTime
?
string input;
DateTime db;
Console.WriteLine("Enter Date in this Format(YYYY-MM-DD): ");
input = Console.ReadLine();
db = Convert.ToDateTime(input);
//////// this methods convert string value to datetime
///////// in order to print date
Console.WriteLine("{0}-{1}-{2}",db.Year,db.Month,db.Day);
Since you are handling 24-hour based time and you have a comma separating the seconds fraction, I recommend that you specify a custom format:
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
DateTime.Parse
Syntax:
DateTime.Parse(String value)
DateTime.Parse(String value, IFormatProvider provider)
DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)
Example:
string value = "1 January 2019";
CultureInfo provider = new CultureInfo("en-GB");
DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););
It's also worth remembering DateTime is an object that is stored as number internally in the framework, Format only applies to it when you convert it back to string.
Parsing converting a string to the internal number type.
Formatting converting the internal numeric value to a readable string.
I recently had an issue where I was trying to convert a DateTime to pass to Linq what I hadn't realised at the time was format is irrelevant when passing DateTime to a Linq Query.
DateTime SearchDate = DateTime.Parse(searchDate);
applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);
Full DateTime Documentation
try this
DateTime myDate = DateTime.Parse(dateString);
a better way would be this:
DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
// handle parse failure
}
Do you want it fast?
Let's say you have a date with format yyMMdd.
The fastest way to convert it that I found is:
var d = new DateTime(
(s[0] - '0') * 10 + s[1] - '0' + 2000,
(s[2] - '0') * 10 + s[3] - '0',
(s[4] - '0') * 10 + s[5] - '0')
Just, choose the indexes according to your date format of choice. If you need speed probably you don't mind the 'non-generic' way of the function.
This method takes about 10% of the time required by:
var d = DateTime.ParseExact(s, "yyMMdd", System.Globalization.CultureInfo.InvariantCulture);