从C#中的DateTime中提取日期部分[重复]

问题描述 投票:59回答:5

这个问题在这里已有答案:

代码行DateTime d = DateTime.Today;导致10/12/2011 12:00:00 AM。我怎样才能得到日期部分。当我比较两个日期时,我需要忽略时间部分。

c# datetime comparison
5个回答
109
投票

DateTime是一个DataType,用于存储DateTime。但它提供了获得Date Part的属性。

您可以从Date Property获取日期部分。

http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx

DateTime date1 = new DateTime(2008, 6, 1, 7, 47, 0);
Console.WriteLine(date1.ToString());

// Get date-only portion of date, without its time.
DateTime dateOnly = date1.Date;
// Display date using short date string.
Console.WriteLine(dateOnly.ToString("d"));
// Display date using 24-hour clock.
Console.WriteLine(dateOnly.ToString("g"));
Console.WriteLine(dateOnly.ToString("MM/dd/yyyy HH:mm"));   
// The example displays the following output to the console:
//       6/1/2008 7:47:00 AM
//       6/1/2008
//       6/1/2008 12:00 AM
//       06/01/2008 00:00

31
投票

没有办法“丢弃”时间组件。

DateTime.Today与以下相同:

DateTime d = DateTime.Now.Date;

如果您只想显示日期部分,只需这样做 - 使用ToString和您需要的格式字符串。

例如,使用standard format string“D”(长日期格式说明符):

d.ToString("D");

14
投票

仅比较数据时间的日期时,请使用Date属性。所以这应该适合你

datetime1.Date == datetime2.Date

11
投票
DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date

如果你想比较日期,忽略时间部分,可以使用DateTime.YearDateTime.DayOfYear属性。

代码段

DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
    Console.WriteLine("d1 < d2");
else
    if (d1.DayOfYear < d2.DayOfYear)
        Console.WriteLine("d1 < d2");

5
投票

你可以使用格式字符串

DateTime time = DateTime.Now;              
String format = "MMM ddd d HH:mm yyyy";     
Console.WriteLine(time.ToString(format));
© www.soinside.com 2019 - 2024. All rights reserved.