Converting a String to a DateTime variable?
How can I c开发者_如何转开发onvert a string "08:00" to a DateTime datatype?
Im trying to use it like this and I get error:
public DateTime currentTime
{
get
{
return DateTime.TryParse(
this.Schedule.Timetables.Max(x => x.StartTime),
currentTime);
}
set
{
currentTime = value;
}
}
/M
You want to look at DateTime.Parse() or DateTime.TryParse().
DateTime.Parse() takes a string, and will throw one of several exceptions if it fails. DateTime.TryParse() takes a string and an out DateTime parameter, and will return a Boolean to determine whether the parse succeeded or not.
You'll also find that you can do this with most other C# struts, such as Boolean, Int32, Double etc...
With the code you have
public DateTime CurrentTime
{
get
{
DateTime retVal;
if(DateTime.TryParse(this.Schedule.TimeTables.Max(x => x.StartTime), out retVal))
{
currentTime = retVal;
}
// will return the old value if the parse failed.
return currentTime;
}
set
{
currentTime = value;
}
}
private DateTime currentTime;
You could also use the DateTime.ParseExact
method
You can use DateTime.ParseExact by passing the string and the exact format( in this case hh:mm)
DateTime.Parse("08:00")
精彩评论