如何从 DateTimeOffset 对象中提取日期

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

如何从 DateTimeOffset 对象中提取日期?我认为 Date 属性只会返回日期部分。但是,我不断获得整个日期时间,即 7/17/2014 12:00:00 AM -04:00。我只想获取日期部分 7/17/2014

这是我的代码。

Func<DataRow, string, DateTimeOffset?> getFieldNullableDate = (row, field) =>
{
  if (!string.IsNullOrWhiteSpace((row[field] ?? string.Empty).ToString()))
      return DateTimeOffset.Parse(row[field].ToString()).Date;
  else
      return null;
};
c# datetime datetimeoffset
5个回答
6
投票

您可以使用它从

MM/DD/YYYY
变量中仅提取
DateTimeOffset?

DateTimeOffset? testOne = null;

var final = testOne.HasValue ? testOne.Value.Date.ToShortDateString() : null;//null

DateTimeOffset? testTwo = new DateTimeOffset(DateTime.Today);

var notNull = testTwo.HasValue 
            ? testTwo.Value.Date.ToShortDateString() 
            : null;// 7/24/2014

2
投票

实际上 DateTimeOffSet 对象具有可以使用的 Date 和 DateTime 属性: 例子

DateTimeOffset? offset = new DateTimeOffset(DateTime.Today);
var dateTime = offset.HasValue ? offset.Value.DateTime : DateTime.MinValue.Date;
var date = offset.HasValue ? offset.Value.Date : DateTime.MinValue.Date;
Console.WriteLine($"date time:{dateTime} and date:{date}");

0
投票

从 DateTime 中删除时间信息

        DateTime now = DateTime.Now;
        DateTime datePart = new DateTime(now.Year, now.Month, now.Day);

0
投票

要仅获取代表当天开始的日期部分,就像

DateTime.Today
所做的那样:

var now = DateTimeOffset.Now;    // 2023-11-12T23:35:37.2256351+03:00
var today = now - now.TimeOfDay; // 2023-11-12T00:00:00.0000000+03:00

这将保留偏移量,并且仍然是

DateTimeOffset
,其中
DateTimeOffset.Now.Date
不会,因为它会返回
DateTime


-1
投票

我没有浏览你的代码,但我相信你正在寻找这个方法:

public string ToShortDateString()

示例:

DateTime thisDay = DateTime.Today;
thisday = thisday.ToShortDateString();
© www.soinside.com 2019 - 2024. All rights reserved.