-1

I am trying to convert MicrosoftDateFormat to DateTime but not sure how to do that. I know how to do the opposite, meaning, convert DateTime to MicrosoftDateFormat. I tried following:

Approach-1:

var input = DateTime.Now;
var jsonMsDate = JsonConvert.SerializeObject(input, new JsonSerializerSettings
{
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});

Output:

"\"\\/Date(1488389116170-0500)\\/\""

What I want is,

Input =  "/Date(1488393000000-0500)/"
Output = DateTime
GThree
  • 2,708
  • 7
  • 34
  • 67
  • 1
    SerializeObject = convert from object to JSON. You're *starting* with JSON, so you should be calling DeserializeObject. Although that's only judging by your final "input / output" part. Your code definitely starts with a DateTime, not a string, making the whole question very confusing. – Jon Skeet Mar 01 '17 at 17:41
  • Note that at least some of the backslashes in the output are probably what you're seeing in the debugger, and not part of the output. It's hard to say. A [mcve] would help... – Jon Skeet Mar 01 '17 at 17:42
  • Check out this SO post with 10 answers and 220 up votes: http://stackoverflow.com/questions/1016847/converting-net-datetime-to-json – smoore4 Mar 01 '17 at 17:57
  • @JonSkeet Sorry about the confusion. Based on your suggestion I have found the solution and posted it below. Thank you – GThree Mar 01 '17 at 17:58
  • @CSharper Mark the correct answer and upvote the value adding answers. – tRuEsAtM Mar 03 '17 at 19:26

2 Answers2

0

Deserialize jsonMSDate, and just verify the type returned. Try following code:

 var datetime = JsonConvert.DeserializeObject(jsonMsDate);
 Console.WriteLine(datetime.GetType());

datetime.GetType() returns System.DateTime as required by you.

tRuEsAtM
  • 3,517
  • 6
  • 43
  • 83
0

After some trial and error, I found the solution:

public static void JsonToDateTime()
{
    var dateObj = new DateTest { Date = "/Date(1488393000000-0500)/" };
    var jsonDate = JsonConvert.SerializeObject(dateObj.Date);
    var output = JsonConvert.DeserializeObject<DateTime>(jsonDate);

}

public class DateTest
{
    public string Date { get; set; }
}

Output:

3/1/2017 1:30:00 PM
GThree
  • 2,708
  • 7
  • 34
  • 67