C# - 计算截止日期之前的小时数 [英] C# - calculate number of hours away from a deadline

查看:185
本文介绍了C# - 计算截止日期之前的小时数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我尝试过这个问题,我需要对最后一部分提供一些帮助。我一直在做研究,因为我是新手,但人们的帮助是有益的。

请看看我到目前为止做了些什么。



问题是,它说以下方法或属性之间的调用是不明确的:'​​Math.Round(double,int)'和'Math.Round(decimal,int)'。



据我所知,我需要将变量转换为十进制或双精度,然后将其舍入为2dp,但是我成功地解决了这个问题(即我知道我想做什么,但就没有错误正确编码而言,我还没有能够做到这一点。



问候。



我的尝试:



Hi,

I have attempted this question and I need a tiny bit of help with the last part. I'm constantly doing research, as I'm new to this, but help from people is beneficial.
Please see what I have done so far below.

The problem is, it is saying that "the call is ambiguous between the following methods or properties: 'Math.Round(double, int)' and 'Math.Round(decimal, int)'.

As far as I am aware, I need to convert the variable into a decimal or a double, and then round this to 2dp, but I am having issues doing this successfully (i.e. I know what I want to do, but as far as coding it correctly without errors, I have not been able to do that as of yet).

Regards.

What I have tried:

public static double HowManyHoursFromNow(DateTime deadline)
{
    var remaining = deadline.Subtract(DateTime.Now).Hours;

    return Math.Round(remaining, 2);
}

推荐答案

时间span有几个属性。你可以获得Days / Hours和Minutes组件,但是:



小时数永远不会超过23.这是在Days属性中处理的。它永远不会比int更精确。这是由Minute属性处理

分钟永远不会超过59.等等...



您要找的是TotalHours。这可以超过23,并且精确到双精度。
Timespan has several properties. You can get the Days/Hours and Minutes components but:

The Hours will never go over 23. this is handled in the Days property. It will never be more precise than and int. this is handled by the Minute property
The minutes will never go over 59. etc...

What you're looking for is the TotalHours. This can be over 23 and is as precise as a double can be.


DateTime.Subtract 方法返回 TimeSpan 对象, Hours 属性是 int 。所以 Math.Round 对它没有任何作用,因为它没有小数部分;你只能围绕<$ h $ => https://msdn.microsoft .com / zh-cn / library / system.math.round(v = vs.110).aspx> Math.Round方法(系统) [ ^ ]。
The DateTime.Subtract method returns a TimeSpan object, and the Hours property of that is an int. So Math.Round cannot do anything with it as it has no fractional part; you can only round a Decimal or Double type as described in Math.Round Method (System)[^].


你应该使用TotalHours属性来代表整个和小时。

You should use the TotalHours property which represents whole and fractional hours.
public static double HowManyHoursFromNow(DateTime deadline)
{
    var remaining = deadline.Subtract(DateTime.Now).TotalHours;

    return Math.Round(remaining, MidpointRounding.AwayFromZero);
}


这篇关于C# - 计算截止日期之前的小时数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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