IBQ
IBQ

Reputation: 13

c#: Get timezone offset stored in date object

I am getting a date from API response as:

string jsonResponse = @"{'endDate': '/Date(-62135578800000-0500)/'}";

Now when I deserialize the reponse using NewtonSoft.json I get the result as:

MyClass obj = JsonConvert.DeserializeObject<MyClass>(jsonResponse);
Console.WriteLine(obj.endDate); // 1/1/0001 5:00:00 AM

Now again after some operation I have to post the data to the server in that same format of the date I have received:

DateTime endDateValue = new DateTime();
endDateValue = obj.endDate

MyClass objNew = new MyClass{
    endDate = endDateValue
};
string jsonPostData = JsonConvert.SerializeObject(objNew);

string response = JsonConvert.SerializeObject(jsonPostData);
Console.WriteLine(response);//{"endDate":"0001-01-01T05:00:00+00:00"}

Since I don't want this format "0001-01-01T05:00:00+00:00". It should be same as '/Date(-62135578800000-0500)/'.

Till now I followed this link to understand the type of format: PHP date format /Date(1365004652303-0500)/

I am able to get the timestamp like this:

DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
long unixTimeStampInTicks = (endDateValue.ToUniversalTime() - unixStart).Ticks;
Console.WriteLine(unixTimeStampInTicks/10000);//-62135578800000

Is there any method in c# to get the offset value -0500 present in this date object like in javascript getTimezoneOffset() method returns the offset.

Upvotes: 1

Views: 507

Answers (1)

j4nw
j4nw

Reputation: 2415

Simply use DateTimeOffset, not DateTime - it's a similar structure, only with an explicit Offset property. Plain DateTime doesn't have a concept of time zones.

This means using it within MyClass, and deserializing to it.

Upvotes: 2

Related Questions