Hi I currently have a TimePicker. It returns an object TimeSpan. What I need to do is to set a DateTimeOffset that is equal to current date plus the TimeSpan from the TimePicker.

How can I actually get the current DateTimeOffset.now that doesn't have a Time on it, only the Date so that I can add the offset to it.

Thanks

有帮助吗?

解决方案

As in DateTime object you have a Date property, it returns date part without time (it means time is 00:00:00).

DateTime today = DateTimeOffset.Now.Date;
DateTime result = today + yourTimeSpan;

With this solution will lost Offset information (because Date is a DateTime). To keep it you just need to subtract time part:

DateTimeOffset now = DateTimeOffset.Now;
DateTimeOffset result = now - now.Time + yourTimeSpan;

Or with constructor:

DateTimeOffset now = DateTimeOffset.Now;
DateTimeOffset result = new DateTimeOffset(now.Date + yourTimeSpan, now.Offset);

其他提示

Can you not just .Date it?

var a = DateTimeOffset.Now.Date;

try using:

DateTime.Today

instead of Now.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top