如何从 DateTimeOffset 对象中提取日期

Ric*_*d77 4 c# datetime datetimeoffset

如何从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;
};
Run Code Online (Sandbox Code Playgroud)

Mic*_*iff 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
Run Code Online (Sandbox Code Playgroud)