I have a a WCF service that returns a CLR object. This object is defined as follows:
[DataContract]
public class Person
{
[DataMember]
public string Full
Well, lately I had to work on an Android Mobile (Xamarin Studio) app project where I was unable to use Newtonsoft Json (Json.NET) due to errors thrown during deployment to this specific device version (Android API 16 Version 4.2.1).
Luckly I found an alternative library for json (System.Json). However this library does not have a way of casting JSON date to C# DateTime implicitly.
I have created the following two functions for nullable date and date conversions from a string json date(i.e /Date(1389435240000+0000)/)
The code can be improved but it does the job for now
public static DateTime? ConvertToNallableDate(string date)
{
DateTime? val = null;
/* /Date(1389435240000+0000)/*/
try{
if(!string.IsNullOrEmpty(date))
{
date = date.Replace ("/Date(", string.Empty).Replace (")/", string.Empty);
int pIndex = date.IndexOf ("+");
if(pIndex < 0) pIndex = date.IndexOf("-");
long millisec = 0;
date = date.Remove (pIndex);
long.TryParse (date, out millisec);
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-GB");
DateTime newDate = DateTime.Parse ("1970,1,1", ci);
newDate = newDate.AddMilliseconds(millisec);
val = newDate == null ? (DateTime?)null : newDate;
}
}catch {
val = null;
}
return val;
}
public static DateTime ConvertToDate(string date)
{
DateTime val = new DateTime();
/*/Date(1389435240000+0000)/*/
try{
if(!string.IsNullOrEmpty(date))
{
date = date.Replace ("/Date(", string.Empty).Replace (")/", string.Empty);
int pIndex = date.IndexOf ("+");
if(pIndex < 0) pIndex = date.IndexOf("-");
long millisec = 0;
date = date.Remove (pIndex);
long.TryParse (date, out millisec);
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-GB");
DateTime newDate = DateTime.Parse ("1970,1,1", ci);
val = newDate.AddMilliseconds(millisec);
}
}catch {
val = new DateTime();
}
return val;
}