Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the easiest way in C# to define a time of day, i.e. HH:MM:SS, without resorting to DateTime which requires year,month,day?

Tags:

c#

.net

I'd like to define a time of day, without necessarily specifying a year, month, day, which would require DateTime.

After I define this Time, I'd like to use all of the nice things about DateTime, i.e. AddMinutes, AddHours, .Hour, .Second, etc.

I guess what I really want the "Time" out of "DateTime", but I can't seem to find it anywhere.

Many thanks in advance!

EDIT:

This is what I was looking for:

// Specify a time of day.
TimeSpan timeSinceMidnight= new TimeSpan(16,00,00); // 4pm
... other code to calculate correct date ...
// Work out scheduled time of day.
DateTime date = new DateTime(2010,12,10).Add(timeSinceMidnight);
like image 984
Contango Avatar asked Nov 22 '25 09:11

Contango


2 Answers

Why not just use the standard .NET DateTime class and ignore the date part? It seems that DateTime.ToShortTimeString() could help, or perhaps DateTime.TimeOfDay, which returns a TimeSpan representing the length of time since midnight.

Any other solution would be reinventing the wheel.

like image 153
Mike Chamberlain Avatar answered Nov 24 '25 23:11

Mike Chamberlain


Take a look at the TimeSpan structure

like image 37
Sam B Avatar answered Nov 24 '25 22:11

Sam B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!