Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert Int into Time in c#?

Tags:

c#

datetime

time

I have integer values like 06,07,08,.....,16,17,18,...

I want to convert this integer values to 24 hour time format.

I am doing something like this

//fromTime holds one of the integer value.
DateTime fromTimeDate = DateTime.ParseExact(fromTime.ToString(), 
                                              "HH", 
                                              CultureInfo.InvariantCulture);  

string fromtimestring = fromTimeDate.ToString("hh:mm tt");

But it is giving Error

"String was not recognized as a valid DateTime."

while parsing.

What I am doing wrong here. ?

like image 282
vaibhav shah Avatar asked Apr 25 '13 07:04

vaibhav shah


People also ask

How do you convert int to time?

To convert number INT in minutes to TIME in MySQL, you can use SEC_TO_TIME() function. Insert some records in the table using insert command.

How to convert int to time in c#?

int val = 16; TimeSpan result = TimeSpan. FromHours(val); string fromTimeString = result. ToString("hh':'mm");

How do you convert integers to seconds?

To convert time to seconds, multiply the time time by 86400, which is the number of seconds in a day (24*60*60 ).

Can we convert int to char in C?

We can convert an integer to the character by adding a '0' (zero) character. The char data type is represented as ascii values in c programming. Ascii values are integer values if we add the '0' then we get the ASCII of that integer digit that can be assigned to a char variable.


1 Answers

Please try this code:

int val = 16;
TimeSpan result = TimeSpan.FromHours(val);
string fromTimeString = result.ToString("hh':'mm");

Actually, I don't think DateTime is the correct type to represent your need, as you only care about the time within a day. A date also represents the day, and you cannot truncate it (as far as I know).

See TimeSpan.FromHours Method

like image 81
Steve B Avatar answered Sep 20 '22 10:09

Steve B