开发者

how to add a DateTimeOffset to a DateTime in C#?

i have a problem, i have a DateTimeOffset and a DateTime, and i want to know how to add the Offset to the DateTime?

DateTimeOffs开发者_如何学Pythonet e.g. is +02:00


Documentation: http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx says that DateTimeOffset already contains both a DateTime and an offset.

You probably want to use a TimeSpan instead of a DateTimeOffset. TimeSpan's can be added to DateTimes.


Sadly, DateTimeOffset is not what a normal person would understand from it's name. Simply put it's a DateTime WITH an offset (maybe not exactly just this; but close enough). Imo this is the worst named class in the whole .NET. The name came straight from SQL Server afaik. You can refer to this for details:

http://www.danrigsby.com/blog/index.php/2008/08/23/datetime-vs-datetimeoffset-in-net/


Assuming that you need to add +2:00 to a DateTime. You can do,

DateTime dateTime = DateTime.Now.AddHours(2.0);


The DateTimeOffset class "represents a point in time, typically expressed as a date and time of day, relative to Coordinated Universal Time (UTC)." It contains both a DateTime value and an offset, so if you want to add the offset to the DateTime, you would want to create a new DateTimeOffset using the constructor, and then use one of the AddX() functions for DateTimeOffset to modify the offset value.

var offset = new DateTimeOffset(DateTime.Now);

See this blog post for examples on how to convert from one to the other, perform arithmetic, etc.


You can achieve it by passing in the relevant values to AddMinutes or AddHours of your DateTime instance

startDate.AddHours(2) will increment the current DateTime object by 2 hours (to decrement it would be -2)

Or you can intialize a Timespan object like

TimeSpan ts = new TimeSpan(2,0,0);

Now you can add this to your DateTime object

startDate= startDate+ ts;


The way to make an offset-less time having an offset (e.g. +02:00) is assuming that timeZone is e.g. 04:00 and utc is a DateTimeOffset structure, initialized on GMT.

var timeZone = TimeZone.FromSeconds(14400)
var localTime= utc.ToOffset(timeZone)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜