Jost Data Date Conversion

Source: Internet
Author: User

In development, it is sometimes necessary to return JSON-formatted data from the server side, and in the background code, if a datetime type of data is serialized using the system's own tool class, a long numeric representation of the date data is given, as follows:

Copy CodeThe code is as follows:
Set the result of the server response to plain text format
Context. Response.ContentType = "Text/plain";
Student Objects Collection
list<student> students = new list<student>
{
New Student () {Name = "Tom",
Birthday =convert.todatetime ("2014-01-31 12:12:12")},
New Student () {Name = "Rose",
Birthday =convert.todatetime ("2014-01-10 11:12:12")},
New Student () {Name = "Mark",
Birthday =convert.todatetime ("2014-01-09 10:12:12")}
};

JavaScript Serializer
JavaScriptSerializer jss=new JavaScriptSerializer ();
Serializing a student collection object to get JSON characters
String STUDENTSJSON=JSS. Serialize (students);
To respond to a string to the client
Context. Response.Write (Studentsjson);
Context. Response.End ();

The operating result is:

Where Tom's corresponding birthday "2014-01-31" became 1391141532000, which is actually the number of milliseconds since January 1, 1970; 1391141532000/1000/60/60/24/365=44.11 years, 44+1970= In 2014, this method can be used to derive the day of the month, minutes and milliseconds. This format is a workable representation but not a friendly format that ordinary people can understand, how to make this format change?

Workaround:

Method 1: Convert the date format to the client by using the Select method or the LINQ expression on the server side:

Copy CodeThe code is as follows:
Using System;
Using System.Collections.Generic;
Using System.Web;

Using System.Web.Script.Serialization;

Namespace JsonDate1
{
Using System.Linq;

<summary>
Student class, for testing
</summary>
public class Student
{
<summary>
Name
</summary>
Public String Name {get; set;}

<summary>
Birthday
</summary>
Public DateTime Birthday {get; set;}
}

<summary>
Returns the JSON character of the student collection
</summary>
public class Getjson:ihttphandler
{
public void ProcessRequest (HttpContext context)
{
Set the result of the server response to plain text format
Context. Response.ContentType = "Text/plain";
Student Objects Collection
list<student> students = new list<student>
{
New Student () {Name = "Tom", Birthday =convert.todatetime ("2014-01-31 12:12:12")},
New Student () {Name = "Rose", Birthday =convert.todatetime ("2014-01-10 11:12:12")},
New Student () {Name = "Mark", Birthday =convert.todatetime ("2014-01-09 10:12:12")}
};

           //Use the Select method to re-project the collection of objects to convert the Birthday property to a new property
           //Note rename after property changes and execute immediately
             var studentset =
                 students. Select
                (
                p = new {p.name, Birthday = p.birthday.tostring ("Yyyy-mm-dd")}
                ). ToList ();

           //javascript Serializer
             JavaScriptSerializer JSS = new JavaScriptSerializer ();
           //Serializing a Student collection object to get JSON characters
             string Studentsjson = JSS. Serialize (Studentset);
           //Response string to client
             context. Response.Write (Studentsjson);
            context. Response.End ();
       }

public bool IsReusable
{
Get
{
return false;
}
}
}
}

The Select method re-projects the collection of objects to convert the Birthday property to a new property, note that the property name can be the same after the property changes, you can use the Select method, or you can use a LINQ query expression or choose another way to achieve the same purpose This method can be used to eliminate the properties of the client in the collection, to achieve the purpose of simple optimization performance.

Operation Result:


Bad HDD data recovery online customer service System simple breast augmentation method re-install system lazy people breast enlargement method

The date format is now a friendly format, but in JavaScript it's just a string.

Method Two:

Converts a string from "Birthday": "\/date (1391141532000) \ \" In JavaScript to a Date object in JavaScript, You can delete the non-numeric word utilises substitution in the value corresponding to the birthday key to a number 1391141532000, then instantiate a Date object with 1391141532000 milliseconds as the argument. Get a Date object in JavaScript with the following code:

Copy CodeThe code is as follows:
<! DOCTYPE html>
<title>json Date format processing </title>
<script src= "Scripts/jquery-1.10.2.min.js" type= "Text/javascript" ></script>
<script type= "Text/javascript" >
$ (function () {
$.getjson ("Getjson.ashx", function (students) {
$.each (students, function (index, obj) {
$ ("<li/>"). html (obj. Name). AppendTo ("#ulStudents");

                    //Use regular expressions to delete a non-number (\d) in the birthday attribute
                    //and convert the resulting number of milliseconds into a numeric type
                     var birthdaymilliseconds = parseint (obj. Birthday.replace (/\d/igm, ""));
                    //Instantiate a new date format, using the number of milliseconds since January 1, 1970 for the parameter
                     var birthday = new Date (birthdaymilliseconds);

$ ("<li/>"). HTML (birthday.tolocalestring ()). AppendTo ("#ulStudents");;
});
});
});
</script>
<body>
<ul id= "Ulstudents" >
</ul>
</body>

Operation Result:

Linux Getting Started file Recovery Acne Simple Small method

The use of the regular/\D/IGM to replace all non-numeric purposes, \d represents non-numeric, IgM is a parameter, respectively, to ignore (ignore) case, multiple, global replacement, multi-line replacement (multi-line), there are some times there will be +86 of the situation, It is also possible to achieve the same goal by simply transforming the regular. Alternatively, if you have recurring problems with the date format that need to be handled in your project, you can extend a JavaScript method with the following code:

Copy CodeThe code is as follows:
$ (function () {
$.getjson ("Getjson.ashx", function (students) {
$.each (students, function (index, obj) {
$ ("<li/>"). html (obj. Name). AppendTo ("#ulStudents");

                 // Use regular expressions to remove non-numbers (\d) from the birthday attribute
                    //and convert the resulting number of milliseconds into a numeric type
                     var birthdaymilliseconds = parseint (obj. Birthday.replace (/\d/igm, ""));
                 // Instantiate a new date format, using the number of milliseconds from January 1, 1970 to the present parameter
                     var birthday = new Date (birthdaymilliseconds);

$ ("<li/>"). HTML (birthday.tolocalestring ()). AppendTo ("#ulStudents");
$ ("<li/>"). html (obj. Birthday.todate ()). AppendTo ("#ulStudents");
});
});
});

Extend a ToDate method in a String object, which can be perfected as required
String.prototype.toDate = function () {
var datemilliseconds;
if (IsNaN (this)) {
Use a regular expression to delete a non-number (\d) in a date property
Datemilliseconds =this.replace (/\d/igm, "");
} else {
Datemilliseconds=this;
}
Instantiate a new date format, using the number of milliseconds from January 1, 1970 to the present
return new Date (parseint (datemilliseconds));
};

The method todate above is not necessarily reasonable or strong enough to be modified as needed.

Method Three:

You can select some third-party JSON tool classes, many of which have already been processed for date format problems, and the common JSON serialization and deserialization ToolPak are:

1.fastJSON.
2.json_checker.
3.Jayrock.
4.json.net-linq to Json.
5.LitJSON.
6.JSON for. NET.
7.JsonFx.
8.JSONSharp.
9.JsonExSerializer.
10.fluent-json
11.Manatee Json

Here is an example of a tool class that Litjson JSON as serialized and deserialized, with the following code:

Copy CodeThe code is as follows:
Using System;
Using System.Collections.Generic;
Using System.Web;

Using Litjson;

Namespace JsonDate2
{
Using System.Linq;

<summary>
Student class, for testing
</summary>
public class Student
{
<summary>
Name
</summary>
Public String Name {get; set;}

<summary>
Birthday
</summary>
Public DateTime Birthday {get; set;}
}

<summary>
Returns the JSON character of the student collection
</summary>
public class Getjson:ihttphandler
{
public void ProcessRequest (HttpContext context)
{
Set the result of the server response to plain text format
Context. Response.ContentType = "Text/plain";
Student Objects Collection
list<student> students = new list<student>
{
New Student () {Name = "Tom", Birthday =convert.todatetime ("2014-01-31 12:12:12")},
New Student () {Name = "Rose", Birthday =convert.todatetime ("2014-01-10 11:12:12")},
New Student () {Name = "Mark", Birthday =convert.todatetime ("2014-01-09 10:12:12")}
};

           //Serializing a Student collection object to get JSON characters
             string Studentsjson = Jsonmapper.tojson (students);
           //Response string to client
             context. Response.Write (Studentsjson);
            context. Response.End ();
       }

public bool IsReusable
{
Get
{
return false;
}
}
}
}

The results of the operation are as follows:


Ding Jie erp-Enterprise whole process management software "Click to enter" Ding-Jie software ERP30 years of professional development, the function of a comprehensive help more than 50,000 enterprises to achieve success!View


The date format is basically correct, so long as the date is instantiated directly in JavaScript,

var date = new Date ("01/31/2014 12:12:12");
Alert (date.tolocalestring ());

The code for the client is as follows:

Copy CodeThe code is as follows:
$ (function () {
$.getjson ("Getjson2.ashx", function (students) {
$.each (students, function (index, obj) {
$ ("<li/>"). html (obj. Name). AppendTo ("#ulStudents");

var birthday = new Date (obj. Birthday);
$ ("<li/>"). HTML (birthday.tolocalestring ()). AppendTo ("#ulStudents");
});
});
});

var date = new Date ("01/31/2014 12:12:12");
Alert (date.tolocalestring ());

Here are three ways to solve the problem of date formatting after serialization in JSON, and there should be a better and more perfect way to tell me. Because a lot of students asked me so I wrote this text, welcome criticism.

Jost Data Date Conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.