从日期/时间字符串中去除时间部分

9

我在数据库中存储了日期和时间,但我只想显示日期本身,而不是两者都显示。当我将日期/时间存储在变量中时,如何仅输出C#中的日期?


你没有说明是将日期显示给用户还是将其转换为某种交换类型的字符串。答案取决于这个问题的答案。 - Eric MSFT
这是一个一段时间前提出的幼稚问题,我同意我的意图并不是很清楚。我相信当时我是在寻找一个用于日期格式化的字符串格式化工具。 - The Muffin Man
6个回答

10

9
DateTime dt = DateTime.Now;
...=dt.ToLongDateString();
...=dt.ToShortDateString();

1
我更喜欢这个答案,因为它使用了当前的文化设置。 - Doggett
我正在寻找的答案是:{0:MM/dd/yy}。 - The Muffin Man

8

如果您只需要System.DateTime结构的日期部分,您可以使用Date属性(System.DateTime.Date)。它会去除小时、分钟、秒和毫秒。

因此,如果您的数据库列数据类型定义为datetime或类似类型(如果数据库支持),则不必使用字符串和字符串格式。


4

这取决于你要将其写入哪里。格式说明符为"{0:d}"或"{0:D}"。但这取决于你是否使用ToString()、ToShortDateString()、ToLongDateString()、某种网格控件或其他完全不同的东西。


1

请使用提供的方法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

1
我假设您有一个类型为 DateTime 的变量。
如果要将其转换为字符串,请使用:
dtVar.ToShortDateString();

如果您需要格式信息,比如.NET控件(如DataGrid),请使用以下内容:
DataFormatString="{0:d}"

两者都会删除DateTime数据的时间部分,并使用当前区域设置


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接