Lasse Edsvik
Lasse Edsvik

Reputation: 9298

Converting a String to a DateTime variable?

How can I convert 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

Upvotes: 1

Views: 323

Answers (4)

Ian
Ian

Reputation: 34489

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;

Upvotes: 5

ebattulga
ebattulga

Reputation: 10981

DateTime.Parse("08:00")

Upvotes: 0

Rune Grimstad
Rune Grimstad

Reputation: 36320

You could also use the DateTime.ParseExact method

Upvotes: 1

rauts
rauts

Reputation: 1018

You can use DateTime.ParseExact by passing the string and the exact format( in this case hh:mm)

Upvotes: 0

Related Questions