格式化日期和时间文本框
Format Date and Time Textboxes
我有两个文本框,一个用于日期,另一个用于时间。然后将输入到这些文本框中的值保存到数据库中。但是当我重新加载页面时,日期和时间已经重新格式化。日期显示为 10/10/2015 00:00:00 但它应该只是日期。并且时间显示为19:00:00,但我不想显示最后的00。
Lookups.CloseTime p = new Lookups.CloseTime(ID);
if (p != null)
{
txtDate.Text = p.CloseDate.ToString();
txtTime.Text = p.CloseTime.ToString();
}
对于数据库:
private DateTime? _CloseDate;
private TimeSpan? _CloseTime;
public DateTime? CloseDate
{
get { return _CloseDate; }
set { _CloseDate = value; }
}
public TimeSpan? CloseTime
{
get { return _CloseTime; }
set { _CloseTime = value; }
}
您可以使用 DateTime.ToShortDateString
or DateTime.ToString("d")
for the DateTime
without time and TimeSpan.ToString("hh':'mm")
作为 TimeSpan
没有秒数:
txtDate.Text = p.CloseDate.ToShortDateString();
txtTime.Text = p.CloseTime.ToString("hh':'mm");
如果 CloseDate
是 Nullable<DateTime>
你必须使用它 Value
属性:
txtDate.Text = p.CloseDate.HasValue ? p.CloseDate.Value.ToShortDateString() : "";
同样适用于 TimeSpan?
:
txtTime.Text = p.CloseTime.HasValue ? p.CloseTime.Value.ToString("hh':'mm") : "";
使用 .Date
将只为您提供时间部分为零的日期部分。它是一个内置的 .NET 方法,将保存任何定制的 ToString() 操作。
eg. DateTime.Now.Date
我有两个文本框,一个用于日期,另一个用于时间。然后将输入到这些文本框中的值保存到数据库中。但是当我重新加载页面时,日期和时间已经重新格式化。日期显示为 10/10/2015 00:00:00 但它应该只是日期。并且时间显示为19:00:00,但我不想显示最后的00。
Lookups.CloseTime p = new Lookups.CloseTime(ID);
if (p != null)
{
txtDate.Text = p.CloseDate.ToString();
txtTime.Text = p.CloseTime.ToString();
}
对于数据库:
private DateTime? _CloseDate;
private TimeSpan? _CloseTime;
public DateTime? CloseDate
{
get { return _CloseDate; }
set { _CloseDate = value; }
}
public TimeSpan? CloseTime
{
get { return _CloseTime; }
set { _CloseTime = value; }
}
您可以使用 DateTime.ToShortDateString
or DateTime.ToString("d")
for the DateTime
without time and TimeSpan.ToString("hh':'mm")
作为 TimeSpan
没有秒数:
txtDate.Text = p.CloseDate.ToShortDateString();
txtTime.Text = p.CloseTime.ToString("hh':'mm");
如果 CloseDate
是 Nullable<DateTime>
你必须使用它 Value
属性:
txtDate.Text = p.CloseDate.HasValue ? p.CloseDate.Value.ToShortDateString() : "";
同样适用于 TimeSpan?
:
txtTime.Text = p.CloseTime.HasValue ? p.CloseTime.Value.ToString("hh':'mm") : "";
使用 .Date
将只为您提供时间部分为零的日期部分。它是一个内置的 .NET 方法,将保存任何定制的 ToString() 操作。
eg. DateTime.Now.Date