c# - JSON to .Net Epoch date conversion -


i have simple webapi project. passing json date in epoch format "pickupbefore":"/date(1485360480-0800)/". when .net catches datetime shows year 1970. suppose january 25, 2017. should in real time?

in .net application, catching date datetime. behind scene datetime structure filled date 1970. looking in structure me convert real time datetime.

i did looked @ , tried how convert epoch time in c#? before asking question, did not solve issue. thank you

the basic problem date string in unix epoch time in seconds microsoft's json date format in unix epoch time in milliseconds, explained in the documentation. json.net automatically recognizes date strings in microsoft format , in doing interprets offset being in ms not seconds, explains why the datetime shows year 1970, 1970 beginning year of unix epoch.

you should fix json date format consistent microsoft's format, "/date(1485360480000-0800)/". better yet, switch iso 8601 format preferred json format dates , times anyway.

if whatever reason cannot correct json format, need disable json.net's automatic datetime recognition , parsing, , create own custom jsonconverter inheriting datetimeconverterbase.

to disable json.net's automatic date recognition, set dateparsehandling = dateparsehandling.none in jsonserializersettings. if cannot modify overall serializer settings, can disable date recognition on containing type applying converter question 40632820 it, e.g.:

[jsonconverter(typeof(dateparsehandlingconverter), dateparsehandling.none)] // disable json.net's built-in date time parsing function. public class rootobject {     public datetime pickupbefore { get; set; } } 

next need write custom jsonconverter. 1 option duplicate logic of newtonsoft's datetimeutils.tryparsedatetime() , datetimeutils.tryparsedatetimeoffset(), in process rewriting datetimeutils.tryparsedatetimemicrosoft() , datetimeutils.tryparsedatetimeoffsetmicrosoft() parse epoch numbers in seconds not milliseconds. started realized there's fair amount of code involved - more appropriate stackoverflow answer. alternative, quick-and-dirty hack insert 000 substring json convert seconds milliseconds, so:

public class microsoftsecondsdatetimeconverter : datetimeconverterbase {     public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer)     {         if (reader.tokentype == jsontoken.null)             return null;         var token = jtoken.load(reader);         if (token.type == jtokentype.string)         {             var s = ((string)token).trim();             if (s.startswith("/date(", stringcomparison.ordinal) && s.endswith(")/", stringcomparison.ordinal))             {                 // ms datetime format in milliseconds shown here:                 // https://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_sidebarb                 // our times offsets in seconds.                 // convert.                 var sb = new stringbuilder("\"\\/date(");                 var insert = "000"; // seconds ms                 (int = 6; < s.length - 2; i++)                 {                     if (s[i] == '-' || s[i] == '+') // time zone marker                     {                         sb.append(insert);                         insert = string.empty;                     }                     sb.append(s[i]);                 }                 sb.append(insert);                 sb.append(")\\/\"");                 s = sb.tostring();                 var dt = new jsonserializer().deserialize(new stringreader(s), objecttype);                 return dt;             }         }          // not microsoft date.         return new jsonserializer().deserialize(token.createreader(), objecttype);     }      public override bool canwrite { { return false; } }      public override void writejson(jsonwriter writer, object value, jsonserializer serializer)     {         throw new notimplementedexception();     } } 

it's not beautiful job done. apply converter type follows:

[jsonconverter(typeof(dateparsehandlingconverter), dateparsehandling.none)] // disable json.net's built-in date time parsing function. public class rootobject {     [jsonconverter(typeof(microsoftsecondsdatetimeconverter))]     public datetime pickupbefore { get; set; } } 

or add jsonserializersettings.converters change deserialization of datetime strings entire data model.

sample fiddle.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -