Warm tip: This article is reproduced from stackoverflow.com, please click
c# xamarin.android xamarin.ios xna

How can I create a counter that counts down to a given time and date?

发布于 2020-04-11 22:34:13

I have a given time and date and I want to create a counter in my game that is counting down to this given date. I want to display the counter in this format: Days/Hours/Minutes/Seconds

How can I convert the DateTime {2/3/2020 12:00:00 AM} to something like this: 0 Days / 9 Hours / 30 Minutes / 20 Seconds ? The counter should run until it has reached the given time {2/3/2020 12:00:00 AM} (0 Days / 0 Hours / 0 Minutes / 0 Seconds).

I get the following date and time from the server but I don't know how to make a counter out of it.

DateTime image

How can I create a counter that counts down to a given time and date?

var NextLeaderboardReset = resultleaderboard.Result.NextReset;
Questioner
Hobbit7
Viewed
38
Jonesopolis 2020-02-02 22:34

A DateTime minus a DateTime will give you a TimeSpan object, which is what you want here. Then you just need to get the correct string format for your countdown:

var countDownEnd = new DateTime(2020,2,3);

var timeSpan = DateTime.Now - countDownEnd;

var countDownString = $"Time left: {timeSpan.ToString(@"dd\:h\:m\:s")}";