I have spent the better part of the last hour trying and testing methods for handling the many inconsistent formats of date and times received from the my Gmail vault API. I finally have a single solution to share with you.
The various forms of datetime from Google
Before I go into my solution, which is simple, let me share what I mean by inconsistencies. I think of a datetime in the format: dd/mm/yyyy hh:mm:ss, or sometimes with year preceding month which precedes day as in: yyyy/mm/dd hh:mm:ss.
I almost never consider the variation which includes a “(day of the week),” preceding the former mentioned formats. This would appear as: Wed, 05/01/2019 10:30:34. Even worse for me then is to having to then contend with every possible timezone or time standard to convert my time.
With the time zones and time standards added in, now we are handling:
Wed, 05/01/2019 10:30:34 -4000 (GMT)
Wed, 05/01/2019 10:30:34 -4000 (CDT)
Wed, 05/01/2019 10:30:34 -4000 (PDT)
Then, as if that wasn’t enough, Google has also graciously elected to write their dates and times differently at random. Where a random assortment of standards or time zones are wrapped in parenthesis and some, for no apparent reason are not. If you have used the Gmail Vault APi, then you also have noticed that some have the preceding day of the week and some date times do not. Fun right?
Wed, 05/01/2019 10:30:34 -4000 CDT
05/01/2019 10:30:34 -4000 UTC
This is all very fun indeed.
In order to deal with this simply I have elected to only wipe away the frustrating days of the week, as I can figure that in SQL later if needed and also to remove any timezone or mentioned time standards. I will instead make the generalization that all timestamps are on Google’s servers and therefore should be consistently applied.
Here is my simple solution.
if (GmailRec.date.Contains(',')) GmailRec.date = GmailRec.date.Remove(0, 4); if (GmailRec.date.Contains('(')) GmailRec.date = GmailRec.date.Remove(GmailRec.date.Length - 5, 5); if (GmailRec.date.Contains("CDT") && !GmailRec.date.Contains('(')) GmailRec.date = GmailRec.date.Replace("CDT",""); _newDate = DateTime.Parse(GmailRec.date).ToLocalTime();
The only real issue with this is that you are not going to get the true time without the standard or time zone that has been included. Perhaps when I have more time to write a more robust solution to this I will provide that, or maybe Google will figure out how to format date times consistently. Based on their handling of YouTube and the Google Drive APIs, I’m not counting on it.