Created
May 10, 2012 02:55
-
-
Save buchizo/2650720 to your computer and use it in GitHub Desktop.
Convert to DateTimeOffset from Json Date(Unix epoch)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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