如何在C#中的datetimepicker上检索和显示日期 [英] How to retrieve and display date on datetimepicker in C#
问题描述
我正在尝试在datetimepicker上显示数据库中的日期,但我遇到此错误:
值01/01/0001 12:00:00 AM对'value'无效。'Value'应该是'MinDate'和'MaxDate'之间的
。参数名称:价值
我尝试过:
dtpTerminationDate.Value =(tm.TerminationDate == null)? DateTime.Now:
Convert.ToDateTime(tm.TerminationDate.ToShortDateString());
i我正在使用自定义格式:dd / MM / yyyy hh:mm:ss
记住:12/31/1900
maxdate:12/31/2090
数据库日期格式:2017-09-14 00:00:00
使用 MinDate [ ^ ]比较值的属性
DateTime defaultDate = DateTime.Now;
dtpTerminationDate.Value =(tm.TerminationDate == null)? DateTime.Now:tm.TerminationDate< dtpTerminationDate.MinDate? defaultDate:tm.TerminationDate;
Quote:值'01 / 01 / 0001 12:00:00 AM对'value'无效。'Value'应该是'MinDate'和'MaxDate'之间的
。参数名称:值
如果仍然出现错误,则需要设置断点并检查数据/时间是否实际上在有效的最小/最大范围内。错误消息强烈暗示,事实并非如此。
这是一个有效的例子:
var testDateString = 2017-09-01 00: 00:00\" 跨度>;
DateTime dateFormatted;
if (DateTime.TryParse(testDateString, out dateFormatted))
{
dateTimePicker1.Value = dateFormatted;
}
else
{
dateTimePicker1.Value = DateTime.Now;
}
此外,日期通常以UTC格式存储在数据库中,除非应用程序已本地化。如果是UTC,则需要在使用之前本地化日期/时间。
I am trying to display date from database on a datetimepicker but i am having this error:
Value of '01/01/0001 12:00:00 AM is not valid for 'value'.'Value'Should be
between 'MinDate'and 'MaxDate'. Parameter name:Value
What I have tried:
dtpTerminationDate.Value = (tm.TerminationDate == null) ? DateTime.Now : Convert.ToDateTime(tm.TerminationDate.ToShortDateString());
i am using custom format: dd/MM/yyyy hh:mm:ss
mindate:12/31/1900
maxdate:12/31/2090
database date format:2017-09-14 00:00:00解决方案use MinDate[^] Property to compare the value
DateTime defaultDate = DateTime.Now; dtpTerminationDate.Value = (tm.TerminationDate == null) ? DateTime.Now : tm.TerminationDate < dtpTerminationDate.MinDate ? defaultDate : tm.TerminationDate;
Quote:Value of '01/01/0001 12:00:00 AM is not valid for 'value'.'Value'Should be
between 'MinDate'and 'MaxDate'. Parameter name:Value
If you are still getting the error, then you need to set a breakpoint and check that the data/time is in fact within the valid min/max ranges. The error message suggests strongly, that this is not the case.
Here is a working example:
var testDateString = "2017-09-01 00:00:00"; DateTime dateFormatted; if (DateTime.TryParse(testDateString, out dateFormatted)) { dateTimePicker1.Value = dateFormatted; } else { dateTimePicker1.Value = DateTime.Now; }
Also, dates are typically stored in databases in UTC format unless the app is localized. If UTC, you will need to localize the date/time before working with it.
这篇关于如何在C#中的datetimepicker上检索和显示日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!