- Home /
Countdown timer into text c#
I have a game that refills energy after one hour. i managed to make the energy fills every hour by storing the Datatime.Now
into a PlayerPrefs.SetString()
and retriving it later on as a long
. What i'm tying to do now is to show the remaining time till the next refill on a text by converting long to string. The problem now is that it cuts the time and the seconds counter is set to 100. how can i make it show as a normal countdown timer? or is there any better way to do this?
long temp1 = Convert.ToInt64(PlayerPrefs.GetString("Current Time"));
long temp = Convert.ToInt64(PlayerPrefs.GetString("End Time"));
long counter = (temp - temp1) / 10000000;
TimeSpan timeSpan = TimeSpan.FromSeconds(3600);
string timeText = string.Format("{0:D2}:{1:D2}", timeSpan.Minutes, timeSpan.Seconds);
countdown.text = counter.ToString(timeText);
Note that i'm a beginner. Thanks in advance.
Why don't you just use Convert.ToDateTime
ins$$anonymous$$d of int64
i tried but got the error cannot implicitly convert type 'System.TimeSpan' to 'System.Datetime'
on line 4
Answer by FlaSh-G · Jul 08, 2017 at 11:02 AM
timeText is built independently of your counter. You throw in timeSpan.Minutes and timeSpan.Seconds which always will be 0 and 0 because you throw in the constant value of 3600. The minutes of a TimeSpan don't include the hours that are accessible in TimeSpan.Hours. Thus, timeText will always be 00:00. So this code
TimeSpan timeSpan = TimeSpan.FromSeconds(3600);
string timeText = string.Format("{0:D2}:{1:D2}", timeSpan.Minutes, timeSpan.Seconds);
is equivalent to this code
string timeText = "00:00";
Throwing in timeText as a parameter for your ToString will do weird things. I think this example will clarify a bit:
print(12345678L.ToString("00:00"));
This will print 123456:78
into your console.
So let's wrap this up from the beginning. You have two longs, a start time and an end time. I assume they're in milliseconds. So you subtract them from one another (try to use more verbose variable names):
long elapsedTime = endTime - startTime;
Then, you make seconds out of it by dividing by 1,000:
elapsedTime /= 1000;
The fact that this is integer division should not matter since rounding down to the nearest second is okay.
Then, you split this into minutes and seconds:
var elapsedMinutes = elapsedTime / 60;
var elapsedSeconds = elapsedTime % 60; // Modulo calculates the remainder of an integer division
Here, integer division is actually vital.
Now, you can create a proper string with the proper values:
string timeText = string.Format("{0:D2}:{1:D2}", elapsedMinutes, elapsedSeconds);
This string can then directly be displayed:
countdown.text = timeText;
Thank you very much for the detailed answer. Honestly, this could't have been explained any better. I had to change the:
elapsedTime /= 1000;
to:
elapsedTime /= 10000000;
so i could get it in the format of 12:34
ins$$anonymous$$d of 123456:78
. Again, thanks for the detailed explanation.