0

It's pretty simple. I have a string

string s = "/Date(1474408920000)/"

And I want to convert it to a date:

DateTime date = JsonConvert.DeserializeObject<DateTime>(s);

But I get the error:

"Error parsing comment. Expected: *, got D. Path '', line 1, position 1."

What's going on here?

Thanks for your help!

2
  • In JavaScript, anything between two '/' represents a regular expression. Commented Sep 23, 2016 at 21:03
  • You'll want to use Parse or tryparse... but first what date format is that? Epoch, Linux / Windows? mmssssDDmmyyyy ? Commented Sep 23, 2016 at 21:06

3 Answers 3

1

Your json string is not valid but can easily be fixed by surrounding it with "

string s = @"""/Date(1474408920000)/""";

Now DateTime date = JsonConvert.DeserializeObject<DateTime>(s); will work

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Very helpful. By the way, make sure you use .ToLocalTime() if you're trying to compare it to other DateTimes in your program!
0
        var LogDate = new DateTime(2016, 9, 20, 22, 2, 0, DateTimeKind.Utc);

        string JsonDate = JsonConvert.SerializeObject(LogDate, new JsonSerializerSettings {
            DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
        });

        Console.WriteLine(JsonDate);
        Console.ReadLine();

Output from this code gives you a proper JSON date format:

"\/Date(1474408920000)\/"

So your string should look like this:

string s = "\"\\/Date(1474408920000)\\/\"";

Comments

0

try serializing the DateTime obj to JSON using below code.

        var dateTime = DateTime.Now;
        var jsonDate = Newtonsoft.Json.JsonConvert.SerializeObject(dateTime, 
                            new Newtonsoft.Json.JsonSerializerSettings() { 
                                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat, 
                                DateParseHandling = Newtonsoft.Json.DateParseHandling.DateTime });

jsonDate would hold this value "\"\\/Date(1474408920000)\\/\"" or something in this format.
Now deserialize your json date string using below code.

var dateObj = Newtonsoft.Json.JsonConvert.DeserializeObject<DateTime>(dateString, 
                            new Newtonsoft.Json.JsonSerializerSettings() { 
                                DateParseHandling = Newtonsoft.Json.DateParseHandling.DateTime, 
                                DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.