从日期/时间字符串中删除时间

我有日期和时间存储在我的数据库中,我不想显示它们,只是日期本身。 当我将日期/时间存储在变量中时,如何仅输出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(); 

如果你需要格式信息让我们说一个.NET控件(比如DataGrid),请使用:

 DataFormatString="{0:d}" 

两者都删除DateTime数据的时间部分并使用当前文化设置。