Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variable for just time

Tags:

c#

I need to create a variable that contains time in the format hh:mm, how shall I do that?

DateTime currentTime = "00:00";

doesn't seem to do the trick. I need to add hours/minutes in a loop to that variable and keep the format "hh:mm". How is that done?

/M

like image 312
Lasse Edsvik Avatar asked Nov 10 '09 09:11

Lasse Edsvik


People also ask

How do you declare a variable as time?

To declare a date variable, use the DECLARE keyword, then type the @variable_name and variable type: date, datetime, datetime2, time, smalldatetime, datetimeoffset. In the declarative part, you can set a default value for a variable.

How do you declare a time variable in C#?

There are two ways to initialize the DateTime variable: DateTime DT = new DateTime();// this will initialze variable with a date(01/01/0001) and time(00:00:00). DateTime DT = new DateTime(2019,05,09,9,15,0);// this will initialize variable with a specific date(09/05/2019) and time(9:15:00).

What is the datatype for time in C#?

In C# a DateTime data type is a struct type that represents an instant of time.

What is a date variable?

A date variable is a type of variable that represents an unknown date value (e.g. 11 June 2001) A date value is any value that you can express using any combination of the day, month, year (including the day of the week) in any sequence of your choice.


3 Answers

Probably use TimeSpan for that?

like image 53
F.P Avatar answered Sep 28 '22 08:09

F.P


You should distinguish between the quantity you're trying to keep track of, and the eventual string formatting. They're different things.

Are you trying to maintain a time of day (in which case using DateTime and ignoring the date part is probably best) or a duration of time (in which case TimeSpan is most appropriate)? Either way, pick your data type, use it in your loop, and then deal with formatting as and when you need to.

(Just as a heads-up, I'm part of a new project called Noda Time which keeps all of these as different types; it's a port of the popular Joda Time project for Java. We're a very long way from releasing anything, but in a year's time I hope it would be the best answer for this question :)

like image 37
Jon Skeet Avatar answered Sep 28 '22 09:09

Jon Skeet


Timespan is your best bet, or use DateTime.toString("hh:mm")

like image 24
Lee Conroy Avatar answered Sep 28 '22 08:09

Lee Conroy