Search code examples
c#datetimedatetimeoffset

How to extract just the date from a DateTimeOffset object


How to extract just the date from a DateTimeOffset object? I thought the Date property would return just the date part. But, I keep getting the whole datetime, i.e. 7/17/2014 12:00:00 AM -04:00. I'd like to get only the date portion 7/17/2014.

Here's my code.

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;
};

Solution

  • You can use this to extract only MM/DD/YYYY from the DateTimeOffset? variable.

    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