Skip to content

Instantly share code, notes, and snippets.

@buchizo
Created May 10, 2012 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save buchizo/2650720 to your computer and use it in GitHub Desktop.
Save buchizo/2650720 to your computer and use it in GitHub Desktop.
Convert to DateTimeOffset from Json Date(Unix epoch)
/// <summary>
/// Convert to DateTimeOffset from Json Date(Unix epoch)
/// </summary>
/// <param name="jsondate">ex: "/Date(1324707957994+0900)/"</param>
/// <returns></returns>
public Nullable<DateTimeOffset> ConvertToDateTimeOffsetFromJsonDate(string jsondate)
{
if (String.IsNullOrEmpty(jsondate)) return null;
Regex regex = new System.Text.RegularExpressions.Regex(@"^\/date\((\d*)([\+\-]?\d*)\)\/+$");
MatchCollection matchCol = regex.Matches(jsondate.ToLower());
if (matchCol.Count == 0) throw new InvalidArgumentException("No match.");
Int64 ticks = Int64.Parse(matchCol[0].Groups[1].ToString());
string stroffset = matchCol[0].Groups[2].ToString();
DateTimeOffset offset;
DateTimeOffset.TryParseExact(stroffset, "zzz", System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.None, out offset);
return new DateTimeOffset(new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(ticks).Add(offset.Offset), offset.Offset);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment