简体   繁体   中英

How would I calculate time left in winform?

Hi any ideas on how to calculate time left to a specific hour, ie we start countdown with if currentTime >= TimeSpan.Parse("06:40") && currentTime <= TimeSpan.Parse("07:25") and then we parse current hour and end hour (in this example 7:25) and make a label show how many minutes and seconds are left. I've tried making something with substracting timespan now and end time timespan but it didn't work out at all.

EDIT: The main idea is something like this, but I can't get it to work by using TimeSpan neither DateTime

string myTime;

void timer()
    {
        var endTime = DateTime.Parse(myTime);
        var beginTime = DateTime.Now.TimeOfDay;
    }

private void timer1_Tick(object sender, EventArgs e)
    {
        var endTime = DateTime.Parse(myTime);
        var beginTime = DateTime.Now.TimeOfDay;
        TimeSpan difference = endTime - beginTime;
        TimeSpan currentTime = DateTime.Now.TimeOfDay;
        if (currentTime >= TimeSpan.Parse("06:40") && currentTime <= TimeSpan.Parse("07:25"))
        {
            label5.Text = "0";
            myTime = "07:25";
            timer();
            label6.Text = difference;
        }
    }

Use DateTime instead of TimeSpan when parsing points in time. TimeSpan is for durations. The difference between two points in time (DateTime) will be a duration (TimeSpan).

var end = DateTime.Parse("21:00");
var now = DateTime.Now;      // Could also be some other point in time
TimeSpan timeLeft = end-now;
Console.WriteLine(timeLeft);

Result:

00:24:25.8581440

If you don't like the seconds and fractions of seconds, you can use a custom format , eg

Console.WriteLine(timeLeft.ToString("hh\\:mm"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM