C# 如何将十进制数转换为时间,反之亦然

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1345599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:26:33  来源:igfitidea点击:

How to Convert decimal number to time or vice versa

c#

提问by

here is an example

这是一个例子

            if 8.30 is there it should be 8 hours 30 minute
            if 8 hour 20 minutes  then 8.20  

           Please tell whether it is possible ? if yes
           how ?      

回答by Eric J.

When people talk about decimal hours, they usually mean 0.1 = 6 minutes.

当人们谈论十进制小时时,他们通常的意思是 0.1 = 6 分钟。

So, the correct formula to convert 8.3 would be:

因此,转换 8.3 的正确公式是:

8 hours + 3 * 6 minutes = 8:18

8 小时 + 3 * 6 分钟 = 8:18

To convert 8:20 to decimal it would be:

要将 8:20 转换为十进制,它将是:

8 + 20/6 = 8.333333 (probably round to 8.3)

8 + 20/6 = 8.333333(可能四舍五入到 8.3)

回答by TheVillageIdiot

If it always be separated with .and you want it for displaying then simply use this:

如果它总是与 . 并且你想要它显示然后简单地使用这个:

var ar="8.30".split(new[]{'.'});

Console.Write("{0} hours {1} minutes",ar[0], ar[1]);

PS: Here we are sure to have two elements in array, but please check length of array arbefore using ar[1]

PS:这里我们肯定数组中有两个元素,但是ar使用前请检查数组的长度ar[1]

回答by Rob

Here's a couple of extension methods (for DateTime and Decimal) that do the job:

这是完成这项工作的几个扩展方法(用于 DateTime 和 Decimal):

public static class DecimalToTimeConverters
{
    public static DateTime ToDateTime(this decimal value)
    {
        string[] parts = value.ToString().Split(new char[] { '.' });

        int hours = Convert.ToInt32(parts[0]);
        int minutes = Convert.ToInt32(parts[1]);

        if ((hours > 23) || (hours < 0))
        {
            throw new ArgumentOutOfRangeException("value", "decimal value must be no greater than 23.59 and no less than 0");
        }
        if ((minutes > 59) || (minutes < 0))
        {
            throw new ArgumentOutOfRangeException("value", "decimal value must be no greater than 23.59 and no less than 0");
        }
        DateTime d = new DateTime(1, 1, 1, hours, minutes, 0);
        return d;
    }

    public static Decimal ToDecimal(this DateTime datetime)
    {
        Decimal d = new decimal();
        d = datetime.Hour;
        d = d + Convert.ToDecimal((datetime.Minute * 0.01));

        return d;
    }
}

I tested this very quickly in an ASP.net webpage (I had a web project open at the time) using the following in a new blank page, and it seemed to work a treat:

我在一个新的空白页面中使用以下内容在 ASP.net 网页(当时我打开了一个 web 项目)中非常快速地测试了这个,它似乎很有效:

protected void Page_Load(object sender, EventArgs e)
{
    Response.Clear();
    Decimal d = new decimal();
    d = 3.45M;
    Response.Write(d.ToDateTime().ToString());
    Response.Write("<br />");
    DateTime d2 = new DateTime(2009, 1, 1, 4, 55, 0);
    Response.Write(d2.ToDecimal().ToString());
}

回答by MaLio

As per Rob but substitute

根据罗布但替代

string[] parts = value.ToString().Split(new char[] { '.' }); 
int hours = Convert.ToInt32(parts[0]); 
int minutes = Convert.ToInt32(parts[1]); 

as

作为

int hours = (int)value; 
int minutes = (int)((value - minutes) * 100); 

no strings or reliance on current culture (the assumption that the '.' is the decimal point)

没有字符串或对当前文化的依赖(假设 '.' 是小数点)

回答by yekta

My approach would look something like this. (This is ruby so you'll have to convert it yourself but the logic is whats important here)

我的方法看起来像这样。(这是 ruby​​,所以你必须自己转换它,但逻辑在这里很重要)

  def zeropad(number)
    return ((number.to_f < 10) ? "0" : "") + number.round.to_s
  end

  def decimal_to_time(value)
    t = value.split(".") #returns an array of ["hour", "minutes"]
    hours, minutes = t[0], t[1]
    minutes = zeropad( (minutes.to_f / 10**minutes.length) * 60 ) # parse the minutes into a time value
    return (minutes.to_i == 0) ? hours : hours + ":" + minutes
  end

  def findTime(value)
    value =~ /^\d+\.\d+/ ? decimal_to_time(value) : value
  end

Where findTime("5.015") gives you the appropriate time value.

其中 findTime("5.015") 为您提供适当的时间值。

I've tested this across the following tests and they all pass.

我已经在以下测试中对此进行了测试,它们都通过了。

     | entered_time   | expected_results|
      | "5.6"         | "5:36"          |
      | "5.9"         | "5:54"          |
      | "5.09"        | "5:05"          |
      | "5.0"         | "5"          |
      | "5.00"        | "5"          |
      | "5.015"       | "5:01"          |
      | "6.03"        | "6:02"          |
      | "5.30"        | "5:18"          |
      | "4.2"         | "4:12"        |
      | "8.3"     | "8:18"           |
      | "8.33"    | "8:20"            |
      | "105.5"       | "105:30"        |
      | "16.7"        | "16:42"         |
      | "Abc"         | "Abc"           |
      | "5:36"    | "5:36"              | 
      | "5:44"    | "5:44"              |   

回答by Steve

How can I parse the txtDuration.TextValue into a decimal value?

如何将txtDuration.TextValue解析为十进制值?

if (txtDuration.Text)
{
    var duration = int.Parse(txtDuration.Text);
    var timespan = Boolean.Parse(hdfToggleDuration.Value) ? new TimeSpan (0, 0, duration, 0) : new TimeSpan (0, duration, 0, 0);
    DateTime end = start.Add(timespan);
}