简体   繁体   中英

How to change Dates format from text (Json string) in c# (or how to get date values from a long string)

I have the Json string

....
{'ItemId':340,'LineId':340,'ItemName':'Trim 1_5A','ItemType':1},{'ItemId':341,'LineId':341,'ItemName':'Trim 1_5B','ItemType':1}]},'Success':true,'Errors':[],'OperationCanceled':false,'ErrorsConcatented':'','ResponseTime':'/Date(1425474069569)/'}

....

....
{'ItemId':350,'LineId':340,'ItemName':'Trim 1_5A','ItemType':1},{'ItemId':341,'LineId':341,'ItemName':'Trim 1_5B','ItemType':1}]},'Success':true,'Errors':[],'OperationCanceled':false,'ErrorsConcatented':'','ResponseTime':'/Date(1425474069569)/'}

....

That text have a datetime 'ResponseTime':'/Date(1425474069569)/ , I want to format( mm-dd-yyyy) this date from that string.

To deserialize the JSON I am using the JavaScriptSerializer. When I try to deserialize my JSON I receive the following error:

/Date(1425473984603)/ is not a valid value for DateTime

How can i do it? i have searched lot of in google, but cant get a solution :(

If is it possible, then please help me..

JSON can be parsed into objects that look like the JSON structure. For example,

{
    days: [
        {name: 'monday', value: 5}, 
        {name: 'tuesday', value: 7}
    ],
    week: 18
}

Will become an object with two properties: days and week . You can then use the object just like any other C# object:

Console.WriteLine(parsed.week); //Prints 18
Console.WriteLine(parsed.days[0].name); //Prints 'Monday'
Console.WriteLine(parsed.days[1].value); //Prints 7

So, on to your actual data:

Your JSON example appears to be slightly malformed, so I modified the start a little bit to make a simple example.

Using JSON.Net (can be installed with NuGet), it can be done like this:

var jsonString = "{data: [{'ItemId':340,'LineId':340,'ItemName':'Trim 1_5A','ItemType':1},{'ItemId':341,'LineId':341,'ItemName':'Trim 1_5B','ItemType':1}],'Success':true,'Errors':[],'OperationCanceled':false,'ErrorsConcatented':'','ResponseTime':'/Date(1425474069569)/'}";
dynamic data = JValue.Parse(jsonString);

Console.WriteLine(data.ResponseTime); //this is your DateTime object
Console.WriteLine(data.ResponseTime.ToString("mm-dd-yyyy")); //Formatted like you wanted it

EDIT: Without packages. How about using System.Web.Helpers.Json?

dynamic data = System.Web.Helpers.Json.Decode(jsonString);

Console.WriteLine(data.ResponseTime); ///Date(1425474069569)/

//Now we need to create a DateTime object from this string.
var timeString = data.ResponseTime.Replace("/Date(", "").Replace(")/",""); //Remove the wrapping
var seconds = long.Parse(timeString)/1000; //Parse the number, and turn it into seconds (it was milliseconds)
var date = new DateTime(1970,1,1,0,0,0).AddSeconds(seconds); //Create a new DateTime object starting on the Unix date, and add the seconds
Console.WriteLine(date.ToString("dd-MM-yyyy"));

And if you don't even have System.Web.Helpers, you could also parse the string manually (Regex.Split, String.Split, String.Replace, etc), and use the above method of creating a DateTime object from the date string.

You should deserialize the JSON string into an object.

You can use Newtonsoft JSON, JavaScriptSerializer Deserilize , or something else. After you have deserialized the JSON content in C#, you will have a DateTime object for the ResponseTime property. Once you have the date object you can give the date format like so...

string mystring = String.Format("{0:MM-dd-yyyy}", dt);          // "03-09-2008"

where dt is your DateTime object and mystring is the string value...

MSDN Custom Date Time formats doc

For Deserialization error

error is /Date(1425473984603)/ is not a valid value for DateTime.

check the slashes in your date here is a similar deserialization error with date objects and JavaScriptSerializer

Date Issue with JavaScriptSerializer

if Date is in this format D:20181116110130+05'30' or D:20181116110130-05'30'

 private static string ConvertInToDateTime(string DateTime)
    {
        string[] SplitDate = DateTime.Split(':');
        string[] SplitDateTime = null;
        if (SplitDate[1].Contains("+"))
            SplitDateTime = SplitDate[1].Split('+');
        else if (SplitDate[1].Contains("-"))
            SplitDateTime = SplitDate[1].Split('-');
        string TimeStamp = SplitDateTime[0].Insert(12, ":").Insert(10, ":").Insert(8, " ").Insert(6, "-").Insert(4, "-");
        return TimeStamp;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM