我在数据库中存储了日期和时间,但我只想显示日期本身,而不是两者都显示。当我将日期/时间存储在变量中时,如何仅输出C#中的日期?
这非常有用:
http://www.csharp-examples.net/string-format-datetime/
针对你的情况,我建议:
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
String.Format("{0:MM/dd/yy}", dt);
DateTime dt = DateTime.Now;
...=dt.ToLongDateString();
...=dt.ToShortDateString();
如果您只需要System.DateTime
结构的日期部分,您可以使用Date
属性(System.DateTime.Date)。它会去除小时、分钟、秒和毫秒。
因此,如果您的数据库列数据类型定义为datetime或类似类型(如果数据库支持),则不必使用字符串和字符串格式。
这取决于你要将其写入哪里。格式说明符为"{0:d}"或"{0:D}"。但这取决于你是否使用ToString()、ToShortDateString()、ToLongDateString()、某种网格控件或其他完全不同的东西。
请使用提供的方法ToShortDateString()。
例如:dateToDisplay.ToShortDateString()
示例
using System;
using System.Globalization;
using System.Threading;
public class Example
{
public static void Main()
{
DateTime dateToDisplay = new DateTime(2009, 6, 1, 8, 42, 50);
CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
// Change culture to en-US.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("Displaying short date for {0} culture:",
Thread.CurrentThread.CurrentCulture.Name);
Console.WriteLine(" {0} (Short Date String)",
dateToDisplay.ToShortDateString());
// Display using 'd' standard format specifier to illustrate it is
// identical to the string returned by ToShortDateString.
Console.WriteLine(" {0} ('d' standard format specifier)",
dateToDisplay.ToString("d"));
Console.WriteLine();
// Change culture to fr-FR.
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
Console.WriteLine("Displaying short date for {0} culture:",
Thread.CurrentThread.CurrentCulture.Name);
Console.WriteLine(" {0}", dateToDisplay.ToShortDateString());
Console.WriteLine();
// Change culture to nl-NL.
Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-NL");
Console.WriteLine("Displaying short date for {0} culture:",
Thread.CurrentThread.CurrentCulture.Name);
Console.WriteLine(" {0}", dateToDisplay.ToShortDateString());
// Restore original culture.
Thread.CurrentThread.CurrentCulture = originalCulture;
}
}
// The example displays the following output:
// Displaying short date for en-US culture:
// 6/1/2009 (Short Date String)
// 6/1/2009 ('d' standard format specifier)
//
// Displaying short date for fr-FR culture:
// 01/06/2009
//
// Displaying short date for nl-NL culture:
// 1-6-2009
DateTime
的变量。dtVar.ToShortDateString();
DataFormatString="{0:d}"
两者都会删除DateTime数据的时间部分,并使用当前区域设置。