Home > Software engineering >  DateTime calculations with TimeOnly struct
DateTime calculations with TimeOnly struct

Time:10-06

First of all, I love the idea of seperate TimeOnly and DateOnly structs, which are available in .NET 6 and allow for a cleaner usage of System.DateTime.

I was wondering: Is it possible to calculate with DateTime and e.g. TimeOnly?

DateTime result = DateTime.Parse("10:00") - TimeOnly.Parse("10:00");
// result == DateTime.Now.Date?

Does this even make sense?

CodePudding user response:

There is no overload of - that takes a DateTime and a TimeOnly. However, TimeOnly has a .ToTimeSpan() method, so you can do like this:

DateTime result = DateTime.Parse("10:00") - TimeOnly.Parse("10:00").ToTimeSpan();
  • Related