C# 不可表示的日期时间

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

un-representable DateTime

c#datetime

提问by user1765862

I have method which expects two datetime parameters

我有需要两个日期时间参数的方法

public  void SomeReport(DateTime TimeFrom, DateTime TimeTo)
{
    // ommited 
    TimeFrom.ToString("ddMMyy"), TimeTo.ToString("ddMMyy")));
    // ommited
}

When I'm sending this params

当我发送这个参数时

 DateTime TimeTo = DateTime.Now;
 DateTime TimeFrom = new DateTime().AddHours(-1);

This error occured:

发生了这个错误:

System.ArgumentOutOfRangeException : The added or subtracted value results in an un-representable DateTime.

System.ArgumentOutOfRangeException :添加或减去的值导致无法表示的 DateTime。

What can be the problem?

可能是什么问题?

采纳答案by Oded

new DateTime()is 01/01/0001 00:00:00which is also DateTime.MinValue.

new DateTime()01/01/0001 00:00:00这也是DateTime.MinValue

You are subtracting one hour from that.

您正在从中减去一小时。

Guessing you are trying to subtract an hour from the TimeTovalue:

猜测您正在尝试从TimeTo值中减去一个小时:

var TimeFrom = TimeTo.AddHours(-1);

回答by Rawling

new DateTime()returns the minimum representable DateTime; adding -1hours to this results in a DateTimethat can't be represented.

new DateTime()返回可表示的最小值DateTime;将-1小时数添加到此结果会导致DateTime无法表示。

You probably want DateTime TimeFrom = TimeTo.AddHours(-1);

你可能想要 DateTime TimeFrom = TimeTo.AddHours(-1);

回答by The_Cthulhu_Kid

try:

尝试:

DateTime TimeTo = DateTime.Now;
DateTime TimeFrom = TimeTo.AddHours(-1);

回答by Yahia

creating a DateTimewith new DateTime()gives you a DateTimewith DateTime.MinValue... from this you actually can't subtract anything... otherwise you get the exception you got... see MSDN

创建一个DateTimewithnew DateTime()给你一个DateTimewith DateTime.MinValue... 从中你实际上不能减去任何东西......否则你会得到你得到的异常......请参阅MSDN

回答by user1874915

In your case TimeFromholds the datetime from which -1 can not be added. You can either invoke

在您的情况下,TimeFrom包含无法添加 -1 的日期时间。您可以调用

DateTime TimeFrom = TimeTo .AddHours(-1);

or

或者

DateTime TimeFrom = new DateTime().now.AddHours(-1);

Both of them yield the same result.

它们都产生相同的结果。

回答by Bahruz Qasimov

Look you date or time data .There not enough digits for date or time Example date must be 8 digit 20140604 and time 6 digit like this 180203.For this reason you are getiing error. i get this error too and find time 18000 and change this to 180000 problem solved.

看看你的日期或时间数据。日期或时间没有足够的数字示例日期必须是 8 位数字 20140604 和时间 6 位数字,如 180203。因此,您正在获取错误。我也收到此错误并找到时间 18000 并将其更改为 180000 问题已解决。

回答by Erdogan

In my error, I used the time as 24:00 instead of 00:00

在我的错误中,我将时间用作 24:00 而不是 00:00