bobek
bobek

Reputation: 8020

c# converting string into date time

I have string like this "24:00:00" and I would like to convert it to time. I tried convert and DateTime.Parse but it seems like it needs a date too. Is there a way to just get time, or do I have to put in a date as well?

Upvotes: 7

Views: 12480

Answers (6)

Jarrett Phillips
Jarrett Phillips

Reputation: 133

You can use DateTimeFormatInfo to format your DateTime.

string strDate = "23:10:00";
DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
dtfi.ShortTimePattern = "hh:mm:ss";
dtfi.TimeSeparator = ":";
DateTime objDate = Convert.ToDateTime(strDate, dtfi);
Console.WriteLine(objDate.TimeOfDay.ToString());

Upvotes: 2

musefan
musefan

Reputation: 48435

I am not sure "24:00:00" is going to be a valid time. Any how, you should not need to specify the date, you can do...

DateTime time = DateTime.ParseExact("23:59:59", "HH:mm:ss", null);

If your time is actually a time of the day, then I would suggest sticking with DateTime. If you are actually using an amount of time (i.e. can be more that 23:59:59) then you could use TimeSpan...

TimeSpan time = TimeSpan.ParseExact("23:59:59", "HH:mm:ss", null);

don't forget, both have a TryParseExact version if you are not sure you input will be valid

Upvotes: 3

Ash Burlaczenko
Ash Burlaczenko

Reputation: 25475

How about

var time = new DateTime.Today;
var str = "24:00:00";
var split = str.split(":");

time.AddHours(Convert.ToInt32(split[0]));
time.AddMinutes(Convert.ToInt32(split[1]));
time.AddSeconds(Convert.ToInt32(split[2]));

Hope this helps.

Upvotes: 0

Bassetassen
Bassetassen

Reputation: 21824

You can use timespan

http://msdn.microsoft.com/en-us/library/system.timespan.aspx

Upvotes: 0

ilivewithian
ilivewithian

Reputation: 19702

I think you need TimeSpan.Parse instead?

Upvotes: 1

Anthony Pegram
Anthony Pegram

Reputation: 126942

If you are only interested in the time component, consider using TimeSpan instead of the full DateTime.

var time = TimeSpan.Parse("23:59:59");

Upvotes: 15

Related Questions