I have a string and I want to convert it from string to datetime. When I'm trying its giving exception. Please suggest me how to do.
string stime = "2014-02-02T24:00:00";
DateTime dtStartDateTime = Convert.ToDateTime(stime);
I have a string and I want to convert it from string to datetime. When I'm trying its giving exception. Please suggest me how to do.
string stime = "2014-02-02T24:00:00";
DateTime dtStartDateTime = Convert.ToDateTime(stime);
This is useful—it does the same thing as DateTime.Parse
, BUT
It returns true
if the parse succeeded, and false
otherwise.
protected void Foo()
{
// Use DateTime.TryParse when input is valid.
string input = "2014-02-02T04:00:00";//"2014-02-02";
DateTime dateTime;
if (DateTime.TryParse(input, out dateTime))
{
lblresult.Text = dateTime.ToString();
}
else {
lblresult.Text = "invalid";
}
}
All answers are wrong, unfortunately. I'm really shocked no one even tested their examples.
.NET doesn't support 24
as an hour. It is not possible to parse your string with DateTime.ParseExact
method. But NodaTime does that. It can parse the value but value parsed as next day's midnight. That's probably because there is no standart 24:00
as an hour.
From Wikipedia;
In the 24-hour time notation, the day begins at midnight, 00:00, and the last minute of the day begins at 23:59. Where convenient, the notation 24:00 may also be used to refer to midnight at the end of a given date – that is, 24:00 of one day is the same time as 00:00 of the following day.
I can't install NodaTime right now I installed NodaTime and but this example probably work works..
using System;
using NodaTime;
using NodaTime.Text;
using System.Xml;
class Test
{
static void Main()
{
string s = "2014-02-02T24:00:00";
var pattern = LocalDateTimePattern.CreateWithInvariantCulture
("yyyy-MM-dd'T'HH:mm:ss");
var dt = pattern.Parse(s).Value;
Console.WriteLine(pattern.Format(dt)); // 2014-02-03T00:00:00
}
}