如何从DateTimeOffsetDateTimeOffset对象中提取日期

本文关键字:提取 取日期 对象 DateTimeOffsetDateTimeOffset | 更新日期: 2023-09-27 18:14:35

如何从DateTimeOffsetDateTimeOffset对象中提取日期?我认为日期属性将只返回日期部分。但是,我一直得到整个日期,即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;
};

谢谢你的帮助。

如何从DateTimeOffsetDateTimeOffset对象中提取日期

您可以使用此命令仅从DateTimeOffset?变量中提取MM/DD/YYYY

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

实际上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}");

删除DateTime中的时间信息

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

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

public string ToShortDateString()

的例子:

DateTime thisDay = DateTime.Today;
thisday = thisday.ToShortDateString();