在 C# 中,如何将 TimeSpan 数据类型转换为 DateTime?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1161807/
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 09:41:48  来源:igfitidea点击:

In C#, how do you convert the TimeSpan datatype to DateTime?

c#.netvbatype-conversionaccess-vba

提问by program247365

I'm converting a small MSAccess application to a web-based ASP.NET app, using C# 3.5. I was wondering what's the best way to work with dates in C#, when converting some of this VBA code over to C#.

我正在使用 C# 3.5 将小型 MSAccess 应用程序转换为基于 Web 的 ASP.NET 应用程序。我想知道在将某些 VBA 代码转换为 C# 时,在 C# 中处理日期的最佳方法是什么。

Here is an example of the VBA Code:

这是 VBA 代码的示例:

Coverage1=IIf(IsNull([EffDate1]),0,IIf([CurrDate]<=[EndDate1],[CurrDate]-[EffDate1],[EndDate1]-[EffDate1]+1))

Here is what my current C# code looks like with the errors denoted in the commented code:

这是我当前的 C# 代码的样子,带有注释代码中指出的错误:

    public DateTime CalculateCoverageOne(DateTime dateEffDateOne, DateTime dateCurrentDate, DateTime dateEndDateOne) 
    {
        if (dateCurrentDate.Date <= dateEndDateOne.Date)
        {
            return null; //Get "cannot convert null to System.DateTime because it is a non-nullable value type" error
        }
        else
        {
            if (dateCurrentDate.Date <= dateEndDateOne)
            {
                return dateCurrentDate.Subtract(dateEffDateOne);  //Gets error "cannot implicitly convert system.timepsan to system.datetime
            }
            else
            {
                return dateEndDateOne.Subtract(dateEffDateOne.AddDays(1)); //Gets error "cannot implicitly convert system.timepsan to system.datetime
            }
        }
    }

采纳答案by dahlbyk

It looks like your VB is actually returning a time span, presumably in days. Here's the closest direct translation:

看起来您的 VB 实际上正在返回一个时间跨度,大概以天为单位。这是最接近的直接翻译:

public TimeSpan CalculateCoverageOne(DateTime EffDate1, DateTime CurrDate, DateTime? EndDate1)
{
    return (EndDate1 == null) ? TimeSpan.Zero :
           (CurrDate < EndDate1) ? (CurrDate - EffDate1) :
           (EndDate1.AddDays(1) - EffDate1);
}

If instead you just wanted a count of days, just return the TimeSpan's Days property:

相反,如果您只想计算天数,只需返回 TimeSpan 的 Days 属性:

public int CalculateCoverageOne(DateTime EffDate1, DateTime CurrDate, DateTime? EndDate1)
{
    return ((EndDate1 == null) ? TimeSpan.Zero :
            (CurrDate < EndDate1) ? (CurrDate - EffDate1) :
            (EndDate1.AddDays(1) - EffDate1)).Days;
}

And for good measure, this is how I would clean up your final version:

为了更好地衡量,这就是我清理您的最终版本的方式:

public int CalculateCoverageOne(DateTime dateCurrentDate, DateTime dateEffectiveDate, DateTime dateEffDateOne, DateTime dateEndDateOne)
{
    TimeSpan ts;
    if (dateEffDateOne == DateTime.MinValue)
    {
        ts = TimeSpan.Zero;
    }
    else if (dateEffectiveDate <= dateEndDateOne)
    {
        ts = dateCurrentDate - dateEffDateOne;
    }
    else
    {
        ts = (dateEndDateOne - dateEffDateOne) + new TimeSpan(1, 0, 0, 0);
    }
    return ts.Days;
}

回答by Matthew Jones

Get the TimeSpan, then subtract that from the DateTime to get the date you want. For your inner IF statement, it would look like this:

获取 TimeSpan,然后从 DateTime 中减去它以获得所需的日期。对于您内部的 IF 语句,它看起来像这样:

TimeSpan estSpan = dateCurrentDate.Subtract(dateEffDateOne);
return dateCurrentDate.Subtract(estSpan);

EDIT: You may also want to return DateTime.MaxValue and have the calling function check for the max value, instead of returning null.

编辑:您可能还想返回 DateTime.MaxValue 并让调用函数检查最大值,而不是返回 null。

回答by Fredrik M?rk

cannot convert null to System.DateTime because it is a non-nullable value type" error

无法将 null 转换为 System.DateTime,因为它是不可为 null 的值类型”错误

The DateTimetype is a value type, which means that it cannot hold a null value. To get around this you can do one of two things; either return DateTime.MinValue, and test for that when you want to use the value, or change the function to return DateTime?(note the question mark), which is a nullable DateTime. The nullable date can be used like this:

DateTime类型是一个值类型,这意味着它不能保持一个空值。为了解决这个问题,你可以做两件事之一;要么 return DateTime.MinValue,并在您想使用该值时对其进行测试,要么将函数更改为 return DateTime?(注意问号),它是可空的DateTime。可以为空的日期可以这样使用:

DateTime? nullable = DateTime.Now;
if (nullable.HasValue)
{
    // do something with nullable.Value
}

cannot implicitly convert system.timepsan to system.datetime

不能将 system.timepsan 隐式转换为 system.datetime

When you subtract a DateTimefrom another DateTime, the result is a TimeSpan, representing the amount of time between them. The TimeSpandoes not represent a specific point in time, but the span itself. In order to get the date, you can use the Addmethod or the Subtractmethod overload of a DateTimeobject that accepts a TimeSpan. Exactly how that should look I can't say, since I don't know what the different dates in your code represent.

当您DateTime从 another 中减去 a时DateTime,结果是 a TimeSpan,表示它们之间的时间量。该TimeSpan不代表一个特定的时间点,而是跨越本身。为了获取日期,你可以使用Add方法或Subtract一个的方法重载DateTime接受一个对象TimeSpan。我不能说它到底应该是什么样子,因为我不知道代码中的不同日期代表什么。

In the last case, you can simply use the return value from the AddDays method, but with a negative value (in order to subtract one day, instead of adding one):

在最后一种情况下,您可以简单地使用 AddDays 方法的返回值,但使用负值(为了减去一天,而不是添加一天):

return dateEffDateOne.AddDays(-1);

回答by VladV

DateTime is a value type. So, you cannot assign null to DateTime. But you can use a special value like DateTime.MinValue to indicate whatever you were trying to indicate by null.

DateTime 是一种值类型。因此,您不能为 DateTime 分配 null。但是您可以使用 DateTime.MinValue 之类的特殊值来指示您试图通过 null 指示的任何内容。

DateTime represents a date (and time), like "July 22, 2009". This means, you shouldn't use this type to represent time interval, like, "9 days". TimeSpanis the type intended for this.

DateTime 表示日期(和时间),例如“2009 年 7 月 22 日”。这意味着,您不应使用此类型来表示时间间隔,例如“9 天”。TimeSpan是用于此目的的类型。

dateCurrentDate.Subtract(dateEffDateOne)(or, equivalently, dateCurrentDate-dateEffDateOne) is a difference between two dates, that is, time interval. So, I suggest you to change return type of your function to TimeSpan.

dateCurrentDate.Subtract(dateEffDateOne)(或等效的dateCurrentDate-dateEffDateOne)是两个日期之间的差值,即时间间隔。因此,我建议您将函数的返回类型更改为 TimeSpan。

TimeSpan is also a value type, so you could use, for instance, TimeSpan.Zero instead of null.

TimeSpan 也是一种值类型,因此您可以使用例如 TimeSpan.Zero 而不是 null。

回答by program247365

After some excellent answers (I've up-voted you guys), I've finally hammered out what I think is my answer. Turns out that returning an int, as the number of days, is what worked for me in this situation.

经过一些出色的答案(我已经投票给你们),我终于敲定了我认为我的答案。事实证明,在这种情况下,返回一个 int 作为天数对我有用。

Thanks everyone, for providing your awesome answers. It helped me get on the right track.

谢谢大家,提供您精彩的答案。它帮助我走上正轨。

    public int CalculateCoverageOne(DateTime dateCurrentDate, DateTime dateEffectiveDate, DateTime dateEffDateOne, DateTime dateEndDateOne)
    {
        //Coverage1=
        //IIf(IsNull([EffDate1]),0,
            //IIf([CurrDate]<=[EndDate1],
                //[CurrDate]-[EffDate1],
                    //[EndDate1]-[EffDate1]+1))

        if (dateEffDateOne.Equals(TimeSpan.Zero))
        {
            return (TimeSpan.Zero).Days;
        }
        else
        {
            if (dateEffectiveDate <= dateEndDateOne)
            {
                return (dateCurrentDate - dateEffDateOne).Days;
            }
            else
            {
                return (dateEndDateOne - dateEffDateOne).Add(new TimeSpan(1, 0, 0, 0)).Days;
            }
        }
    }