Change server time to local time that is sent by Facebook

I am using Facebook C# SDK to get some data from my Facebook page.

When I get objects of data, at that time I get one field:

created_time : 2014-05-23T11:55:00+0000

As it is not same as my current time how do I convert it to my current time or to standard UTC time?

Jon Skeet
people
quotationmark

I would use DateTimeOffset.ParseExact, specifying the format string an the invariant culture:

DateTimeOffset value = DateTimeOffset.ParseExact(text, "yyyy-MM-dd'T'HH:mm:ssK",
                                                 CultureInfo.InvariantCulture);

I strongly recommend this over using DateTime.Parse for the following reasons:

  • This always uses the invariant culture. It's explicitly stating that you don't want to use the local culture, which might have a different default calendar system etc
  • This specifies the format exactly. If the data becomes "10/06/2014 11:55:00" you will get an exception, which is better than silently guessing whether this is dd/MM/yyyy or MM/dd/yyyy
  • It accurately represents the data in the string: a date/time and an offset. You can then do whatever you want with that data, but separating the two steps is clearer

The first two of these can be fixed by using DateTime.ParseExact and specifying the culture as well, of course.

You can then convert that to your local time zone, or to any other time zone you want, including your system local time zone. For example:

DateTimeOffset localTime = value.ToLocalTime(); // Applies the local time zone

or if you want a DateTime:

DateTimeOffset localTime = value.ToLocalTime().DateTime;

It's just one extra line of code, but it makes it clearer (IMO) what you're trying to do. It's also easier to compare DateTimeOffset values without worrying about what "kind" they are, etc.

In fact, I wouldn't personally use DateTimeOffset or DateTime - I'd use OffsetDateTime from my Noda Time project, but that's a different matter.

people

See more on this question at Stackoverflow