Reputation: 12636
I receive a DateTime from the client: DateTime CurrentTimeOnClient
I have a DateTimeOffset I get from the db: DateTimeOffset DateTimeOffsetFromDb
I need to compare the two dates, IGNORING the time AND time zone. In other words, I just want the raw date from both objects. I tried using FooDateTimeOffset.DateTime.Date
but it seems to still factor in the time, so what I have now is this:
DateTimeOffset clientDateTimeOffSet = DateTime.SpecifyKind(CurrentTimeOnClient, DateTimeKind.Utc);
clientDateTimeOffSet = await RemoveTimeComponentFromDateTimeOffset(clientDateTimeOffSet);
clientDateTimeOffSet = await SetTimeZoneOffsetToZero(clientDateTimeOffSet);
And the helper methods:
public async Task<DateTimeOffset> SetTimeZoneOffsetToZero(DateTimeOffset dateTimeOffSetObj)
{
TimeSpan zeroOffsetTimeSpan = new TimeSpan(0, 0, 0, 0, 0);
return dateTimeOffSetObj.ToOffset(zeroOffsetTimeSpan);
}
public async Task<DateTimeOffset> RemoveTimeComponentFromDateTimeOffset(DateTimeOffset dateTimeOffSetObj)
{
DateTime dateWithZeroedTime = new DateTime(dateTimeOffSetObj.Year, dateTimeOffSetObj.Month, dateTimeOffSetObj.Day, 0, 0, 0);
return dateWithZeroedTime;
}
Then I clean the DateTimeOffset obj from the db in the same way (though obviously without the need to convert them) and compare them.
bool foo = dateFromDb > dateFromClient;
P.S. I am aware that these questions HAVE been answered separately, but I would like to see if I made any glaring mistakes or if I am overdoing it. (but again, the suggested .Date
solution doesn't seem to work).
Edit: @James
//TESTING
var testDateAndTime = new DateTimeOffset(2008, 5, 1, 8, 6, 32,new TimeSpan(1, 0, 0));
//This is just some db object that has a date field that I had on hand
var anncmnt = db.Announcements.First(a => a.Id == 13);
//CLEAN TIME AND DATE
testDateAndTime = testDateAndTime.DateTime.Date;
anncmnt.EndDate = testDateAndTime;
await db.SaveChangesAsync();
//TESTING
Db Result: 2008-05-01 00:00:00.0000000 -04:00
Upvotes: 3
Views: 8996
Reputation: 129
Forgot UTC. Try using the SpecifyKind method. It appears to give what you need and passes my quick unit test below:
//TESTING
for (var hr = 0; hr < 24; hr++)
{
var testDateAndTime = new DateTimeOffset(2008, 5, 1, hr, 6, 32, new TimeSpan(1, 0, 0));
var noOffsetDate = DateTime.SpecifyKind(testDateAndTime.Date, DateTimeKind.Utc);
Console.WriteLine(noOffsetDate);
}
Upvotes: 1
Reputation: 469
That is weird that the .Date() doesn't work. This is something I've done in the past when addressed with an issue like this. I parse the datetime date string then compare. So I do the below code.
dateFromDb = DateTime.Parse(dateFromDb.ToShortDateString());
dateFromClient= DateTime.Parse(dateFromClient.ToShortDateString());
Then try comparing it and see if that works?
Upvotes: 1