如何在C#中将日期转换为整数? [英] How do I convert the dates to integer in C#?

查看:528
本文介绍了如何在C#中将日期转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是在进度条上显示倒计时进度,但我不知道如何将日期转换为整数以计算进度条的百分比?



谢谢。



我的尝试:



What I want to do is to show the countdown progress on the progress bar, but I don't know how to convert the dates to integers in order to calculate the percentage for the progress bar?

Thank you.

What I have tried:

public Form1()
{
    Timer t = new Timer();
    t.Interval = 1000;
    t.Tick += countdown;
    t.Start();

}

private void countdown(object sender, EventArgs e)
{
    DateTime endDate = DateTime.Parse("12/24/2017");
    DateTime startDate = DateTime.Now;

    TimeSpan timeDiff = endDate - startDate;
    int timeDiffPercent = (timeDiff / endDate) * 100; //How?
    timeLeft.Text = dateDiff;

    timeLeftBar.Value = timeDiffPercent;
}

推荐答案

问题是完成的百分比是固定范围的移动值:和每个Tick都没有引用固定的开始,而是使用当前时间。

首先设置一个固定的开始和结束:

The problem is that the percentage completed is a moving value of a fixed range: and every Tick you do not reference a fixed start, but use the current time instead.
Start by setting a fixed start and end:
private DateTime dtStart;
private DateTime dtEnd;
public Form1()
    {
    Timer t = new Timer();
    t.Interval = 1000;
    t.Tick += countdown;
    dtStart = DateTime.Now;
    dtEnd = new DateTime(2017, 12, 24);
    t.Start();
    }

然后在勾选计算中使用它们:

And then use them in the tick calculation:

private void countdown(object sender, EventArgs e)
    {
    DateTime now = Datetime.Now;
    double total = (dtEnd - dtStart).TotalMinutes;
    double elapsed = (now - dtStart).TotalMinutes;
    double percent = (elapsed / total) * 100.0;
    ...
    }


// the start date will be 1 Jan of the current year
DateTime startDate = new DateTime(DateTime.Now.Year, 1, 1);
DateTime endDate = DateTime.ParseExact("12/24/2017", "MM/dd/yyyy", System.Globalization.CultureInfo.CurrentCulture);

// in this example I'm going to get the % for all days from start to finish
// you're only really interested in currentDate = DateTime.Now and don't need
// the while loop
DateTime currentDate = startDate;

while (currentDate <= endDate)
{
    // get the ticks relative to start date.  Google for what ticks are
    // but they are effectively a numeric value for a date
    long endTicks = endDate.Ticks - startDate.Ticks;
    long nowTicks = currentDate.Ticks - startDate.Ticks;

    // now get the % using traditional maths
    int pc = (int)(decimal.Divide(nowTicks, endTicks) * 100);

    System.Diagnostics.Debug.WriteLine(string.Format("Date: {0} {1}%", currentDate, pc));

    currentDate = currentDate.AddDays(1);

}


这篇关于如何在C#中将日期转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆