How to Convert Int into Time in c#?
Solution 1
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).
Solution 2
The easiest thing to do would be something like:
DateTime time = Date.Today + new TimeSpan (0, 0, seconds);
Solution 3
It can only fail due to two possible reasons.
- First your
fromTime
is holding single digit integer, from0
to9
, and since its9
not09
it would fail with formatHH
. - Second reason could be if the integer is greater than
23
or less than0
.
You can modify your format to single digit H
which would work for both.
DateTime fromTimeDate = DateTime.ParseExact(fromTime.ToString(), "H", CultureInfo.InvariantCulture); //fromTime holds one of the integer value.
The above would parse any number from 0
to 23
.
By the way it more looks like TimeSpan
then DateTime
, you can convert it to TimeSpan
using TimeSpan.FromHours method.
int fromTime = 23;
TimeSpan ts = TimeSpan.FromHours(fromTime);
Solution 4
The "HH" format needs two digits, and 09
as integer is just "9".
Use a fromTime.ToString("00")
there to force a leading 0.
Note that the date part of that DateTime will be "today".
Solution 5
The code you have written is correct please check once...........
"fromTime" values may be single digit like "6" instead "06" or "0" or "Other number more than 24"
"String was not recognized as a valid DateTime." You will get this error when you use "hh" instead "HH" in below line ..............
DateTime fromTimeDate = DateTime.ParseExact(fromTime.ToString(), "HH",
CultureInfo.InvariantCulture);
vaibhav shah
Updated on July 17, 2022Comments
-
vaibhav shah almost 2 years
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. ?
-
vaibhav shah about 11 yearsI am having Time field in MYSql db . Will this work with it ?
-
Steve B about 11 yearsI don't know, but it looks like the time type is closer to the Timespan type in .Net than Datetime.
-
Wai Ha Lee over 8 yearsCan you explain your answer please? 'Teach a man to fish' etc.
-
praveen over 8 yearsmine? you want me to explain?
-
praveen over 8 yearsif you give a integer value for example 1020 it will be returning a string value 10:20......... It will work even if u give 920 ...It will return 09:20