3

An ajax request sends a date value in WCF format? It's a javascript date object converted to a string WCF can deserialize using the DataContractSerializer.

"/Date(1342210377000)/"

the client used to send this data to a WCF service, but now this is sent to an asp.net mvc controller. Does anyone know how I can deserialize that string into a c# DateTime without doing a bun of string.replace operations? Is there an existing .NET serializer I can leverage? I looked at using the DataContractSerializer but it's readobject method takes a stream or xmlreader. I could not figure out how convert a modelbindercontext.valueprovider value to a stream object the serializer could use. If anyone knows how I can correctly convert that string I would love to learn how. Thanks for any tips, tricks, code, links, etc...

Hcabnettek
  • 12,678
  • 38
  • 124
  • 190
  • 1
    Not a C# solution, but a general idea: Use a regexp like `\d{1,}` to get the numeric value, divide by `1000` to get UNIX timestamp and use http://stackoverflow.com/a/250400/759049 to get the desired `DateTime`. – Pateman Jul 13 '12 at 21:00
  • Didn't this post help you? http://stackoverflow.com/questions/259005/handling-wcf-deserialization-of-datetime-objects – CodeMad Jul 13 '12 at 21:05
  • I don't think that this is the only part you have to deserialize. If you show the whole string you get from client you can get a better answer. – L.B Jul 13 '12 at 22:05

2 Answers2

5

You can use the DataContractJsonSerializer to convert that into a DateTime value:

var str = "\"/Date(1342210377000)/\"";
var dcjs = new DataContractJsonSerializer(typeof(DateTime));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(str));
var dt = dcjs.ReadObject(ms);
Console.WriteLine(dt);
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
-3
DateTime.ToUniversalTime()

Say for example, this gives you the output format as "YYYY-MM-DD hh:mm:ss" than take that and let your C# code do the formatting part however you want.

CodeMad
  • 950
  • 2
  • 12
  • 30
  • -1 OP has a string ( `"/Date(1342210377000)/"` ) not a DateTime and asks how to convert it to DateTime – L.B Jul 13 '12 at 22:26