Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Gmail Date to your DateTime as displayed in Gmail Account

I am getting inbox messages using Gmail API in my c# ASP.net application. All messages are from different time zones(states/countries), I wanna display there date in my own time zone as it displays in Gmail App. I searched a lot for conversion between timezones but can't solve it may be i am not getting it properly.

My code for but i tried so far is: (Its working for most of messages but for few of them its not displaying right DateTime)

For Example:

Time displayed in Gmail App: 30/11/2017 2:11 AM

My code Input/ value from Gmail API: Wed, 29 Nov 2017 10:11:35 -0800

Below are some values i am getting from my current gmail inbox messages:

enter image description here

 var re = service.Users.Messages.List("me");
 re.LabelIds = "INBOX";
 re.Q = "is:all";
 var res = re.Execute();
 if (res != null && res.Messages != null)
 {               
   foreach (var email in res.Messages)
   {    
     var emailInfoResponse = service.Users.Messages.Get("me", email.Id).Execute();
    if (emailInfoResponse != null)
    {
      foreach (var mParts in emailInfoResponse.Payload.Headers)
      {
        if (mParts.Name == "Date")
        {
          date = mParts.Value;
        }          
      }
    }
  }
}

My Time Zone is: (UTC+08:00) Perth

Any help would be appreciated. Thanks!

like image 931
Preet Avatar asked Nov 30 '17 01:11

Preet


1 Answers

{
  "id": string,
  "threadId": string,
   ....
  "internalDate": long,
  "payload": {
   ....

internalDate long
The internal message creation timestamp (epoch ms), which determines ordering in the inbox. For normal SMTP-received email, this represents the time the message was originally accepted by Google, which is more reliable than the Date header. However, for API-migrated mail, it can be configured by client to be based on the Date header.

REF: https://developers.google.com/gmail/api/v1/reference/users/messages

Based on the above Google documentation, here's one way:

//Some epoch time in ms
var gmail_date = 1512007768005; 

//Get DateTime of epoch ms
var to_date = DateTimeOffset.FromUnixTimeMilliseconds(gmail_date).DateTime;

//This is your timezone offset GMT +8
var offset = 8;

Console.WriteLine(to_date - new TimeSpan(offset *-1, 0, 0));

Gets you 11/30/2017 10:09:28 AM

like image 127
EdSF Avatar answered Sep 30 '22 11:09

EdSF