Reputation: 3444
Trying to parse JToken which is holding datetime as string, as string. Implicitly what it is doing is considering it as DateTime, parsing and then passing back as string.
Original value is : "2015-11-23T00:00:00"
When I do arr["value"].ToString();
I get : "23/11/2015 00:00:00"
What I really want is whatever was passed i.e. the original value.
Have tried using Formatting.None
, but that brings in double quotes etc.
Is there a simple way round?
Upvotes: 25
Views: 15982
Reputation: 508
My solution to this problem:
public static string DateToStringExact(dynamic date)
{
string dateString = date.ToString(Formatting.None); // return "2021-01-01T00:00:00"
// To return only 2021-01-01T00:00:00 (without ""):
string res = dateString.Substring(1, dateString.Length-2);
//or
string res = dateString.Replace("\"", "");
return res;
}
You can call this function by:
string x = DateToStringExact(arr["value"])
Upvotes: 2
Reputation: 7
First SerializeObject
and then DeserializeObject
to get the safe value of the date field.
JsonConvert.DeserializeObject(JsonConvert.SerializeObject(value);
Upvotes: -3
Reputation: 898
Use DateParseHandling
to override JSON.NET's automatic attempts to DateTimeify anything that looks DateTimey.
void Main()
{
var s = "{ \"value\" : \"2015-11-23T00:00:00\" }";
using (var sr = new StringReader(s))
using (var jr = new JsonTextReader(sr) { DateParseHandling = DateParseHandling.None })
{
var j = JToken.ReadFrom(jr);
Console.WriteLine(j["value"].ToString()); // prints '2015-11-23T00:00:00'
}
}
Upvotes: 26
Reputation: 34224
You can describe the class with this member declared as 'string' and use it in serialization, so that it is is stored in the original representation:
public class MyObject
{
public string date { get; set ; }
}
string json = "{ \"date\": \"2015-11-23T00:00:00\" }";
var myObj = JsonConvert.DeserializeObject<MyObject>(json);
Console.WriteLine(myObj.date);
Upvotes: 1