3

I want to create a new DateTimeOffset with offset = -5 from a string

I do :

string dt = "11082016";    
DateTime date = DateTime.ParseExact(dt, "MMddyyyy", 
                                    CultureInfo.InvariantCulture, 
                                    DateTimeStyles.None);    
DateTimeOffset dto = new DateTimeOffset(date, TimeSpan.FromHours(-5));

Is it possible to create directly a DateTimeOffset without passing by DateTime ?

3
  • DateTimeOffset dto = new DateTimeOffset(2016, 11, 8, 0, 0, 0, TimeSpan.FromHours(-5)); Commented Nov 8, 2016 at 0:36
  • Can you give any reason of using DateTimeOffset, instead of DateTime, or TimeSpan? Commented Nov 8, 2016 at 1:34
  • @LeiYang I need to use this for work with time zone awareness Commented Nov 8, 2016 at 6:02

2 Answers 2

4

Sure you can:

string dt = "11082016";
string o = "-5";
var dto = DateTimeOffset.ParseExact(dt + o, "MMddyyyyz", CultureInfo.InvariantCulture);

Though it's not very pretty - the point is DateTimeOffset also has a ParseExact method.

Sign up to request clarification or add additional context in comments.

Comments

2

Is it possible to create directly a DateTimeOffset without passing by DateTime ?

No, that's not possible.

Every DateTimeOffset instance has to have it's DateTime part. You can't create a DateTimeOffset instance just with a UTC Offset value.

Of course it has some constructors that doesn't take DateTime as a parameter directly like;

  • DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, TimeSpan)
  • DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan)
  • DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan)
  • DateTimeOffset(Int64, TimeSpan)

But those Int32 and Int64 values are still generate a Datetime internally for current instance .DateTime property.

I want to create a new DateTimeOffset with offset = -5 from a string

If you could do that, you wouldn't need that string, don't you think?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.