开发者

Converting a String to a DateTime variable?

开发者 https://www.devze.com 2022-12-11 16:34 出处:网络
How can I c开发者_如何转开发onvert a string \"08:00\" to a DateTime datatype? Im trying to use it like this and I get error:

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")

0

精彩评论

暂无评论...
验证码 换一张
取 消