Convert Time 24 hours to 00 hours

Asked

Viewed 724 times

1

I have an int account, I need to return it for hours, and it is working perfectly, the error occurs when the time appears 24, and it should appear 00:00. Go on like I’m doing:

string horaStg;
decimal valor = int.Parse(item.HoraInicio);
valor = (valor / 60);
var inicio = valor.ToString().Split(char.Parse(","));
string hora = inicio[0];
try
{
    string minuto = "0," + inicio[1];
    string m = Math.Round(decimal.Parse(minuto.ToString()) * 60).ToString();
    horaStg = DateTime.Parse(hora + ":" + m.Substring(0, 2)).ToString("HH:mm");
}
catch
{
    horaStg = DateTime.Parse(hora + ":" + "00").ToString("HH:mm");
}

How can I convert to appear at 00:00 ? 'Cause the way it is when it’s midnight, it pops 24 and returns me the following error:

The Datetime represented by the string is not supported in Calendar System.Globalization.Gregoriancalendar.

I did an if, so:

if (hora == "24")
{
    hora = "00";
}

But there is no conversion that you do directly ?

  • 3

    How about using the module? (valor/60) % 24

  • Could you explain to me the function of %24 please ? I will take the test here.

  • 1

    @marianac_costa could clarify better what you want to do with this code, by chance your item.HoraInicio would be the total of minutes and you want to convert this to the minutes hours format "HH:mm"?

  • The % is the module operator, or the rest of the division. Then, 27%24 would return 3, which is the rest of the division; 3 % 24 returns 3 and 24 % 24 returns 0, since it is a division without rest

  • I used this operation in this answer: https://answall.com/a/294998/64969

  • Got it @Jeffersonquesado gave it right, thank you.

Show 1 more comment

1 answer

1

If you take your Datetime variable and make a Tostring on it passing the hour format with the letter "H" uppercase, it will already appear in the 00-hour format.

Uppercase "HH" format appears in 24-hour format. Lowercase "hh" format appears in 12 hours AM/PM format.

Example:

DateTime data = new DateTime(2018, 06, 29, 00, 11, 49);

Console.WriteLine(data.ToString("HH:mm:ss"));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.