简体   繁体   English

如何在C#中从文本(Json字符串)更改日期格式(或如何从长字符串获取日期值)

[英]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. 该文本具有日期时间'ResponseTime':'/Date(1425474069569)/ ,我想从该字符串格式化(mm-dd-yyyy)此日期。

To deserialize the JSON I am using the JavaScriptSerializer. 为了反序列化JSON,我使用了JavaScriptSerializer。 When I try to deserialize my JSON I receive the following error: 当我尝试反序列化JSON时,出现以下错误:

/Date(1425473984603)/ is not a valid value for DateTime / Date(1425473984603)/不是DateTime的有效值

How can i do it? 我该怎么做? i have searched lot of in google, but cant get a solution :( 我已经在Google中搜索了很多,但无法找到解决方案:(

If is it possible, then please help me.. 如果可以的话,请帮帮我..

JSON can be parsed into objects that look like the JSON structure. JSON可以解析为类似于JSON结构的对象。 For example, 例如,

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

Will become an object with two properties: days and week . 将成为具有两个属性的对象: daysweek You can then use the object just like any other C# object: 然后,您可以像使用任何其他C#对象一样使用该对象:

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. 您的JSON示例似乎格式不正确,因此我对起始内容做了一些修改,以使其成为一个简单的示例。

Using JSON.Net (can be installed with NuGet), it can be done like this: 使用JSON.Net (可以与NuGet一起安装),可以像这样完成:

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? 如何使用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. 而且,即使您没有System.Web.Helpers,也可以手动解析字符串(Regex.Split,String.Split,String.Replace等),并使用上述方法从日期创建DateTime对象串。

You should deserialize the JSON string into an object. 您应该将JSON字符串反序列化为一个对象。

You can use Newtonsoft JSON, JavaScriptSerializer Deserilize , or something else. 您可以使用Newtonsoft JSON,JavaScriptSerializer Deserilize或其他方式。 After you have deserialized the JSON content in C#, you will have a DateTime object for the ResponseTime property. 在C#中反序列化JSON内容之后,您将拥有ResponseTime属性的DateTime对象。 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... 其中dt是您的DateTime对象,而mystring是字符串值...

MSDN Custom Date Time formats doc MSDN自定义日期时间格式文档

For Deserialization error 对于反序列化错误

error is /Date(1425473984603)/ is not a valid value for DateTime. 错误是/ Date(1425473984603)/不是DateTime的有效值。

check the slashes in your date here is a similar deserialization error with date objects and JavaScriptSerializer 检查日期中的斜线,这是日期对象和JavaScriptSerializer的类似反序列化错误

Date Issue with JavaScriptSerializer JavaScriptSerializer的日期发布

if Date is in this format D:20181116110130+05'30' or D:20181116110130-05'30' 如果日期的格式为D:20181116110130 + 05'30'或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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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