The misunderstanding of fish Li in ASP. NET's frequently overlooked details on how. Net javascriptserializer processes datetime

Source: Internet
Author: User
Tags mozilla developer network

Fish Li today published a popular article ASP. net is often overlooked in some of the details, one of which I think he has wronged Microsoft. net class library designer, you open the link and directly jump to the key, paste it first and reference it as follows:

Fish LiJSON serialization of datetime

In sp. in net3.5, Microsoft is ASP. net is designed as a tool class for JSON serialization. web. script. serialization. javascriptserializer, which is widely used and has better compatibility than the JSON serialization class in WCF. However, there is a problem with this class. When serializing the datatime type, the results it generates will make everyone feel awkward. In fact, the serialization result is still a small problem, write a conversion function on the front end. However, if you needObject persistence using serialization and deserialization Methods, You will encounter problems, such as the following code:

DateTime dt1 = DateTime.Now;JavaScriptSerializer jss = new JavaScriptSerializer();string json = jss.Serialize(dt1);DateTime dt2 = jss.Deserialize<DateTime>(json);context.Response.Write(dt1 == dt2);

The result displayed by the browser is surprising. It turns out to be: false.

This reason is related to the time format of JavaScript. It uses UTC time. However, this reason is unacceptable. After all, other deserialization methods can restore objects, for example, both binary serialization and XML can correctly restore objects. No way, this is only a pitfall. Therefore, if you want to perform Object Persistence operations, try not to select JSON serialization.

The above complaints are actually not correct understanding of JavaScript time, in Mozilla Developer Network read an article, introducing JS date object, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date? Redirectlocale = en-US & redirectslug = JavaScript % 2 freference % 2fglobal_objects % 2 fdate

The original description of the date object is as follows:

Description

If you supply no arguments, the constructor creates a javascriptDateObject for today's date and time according to local time. if you supply some arguments but not others, the missing arguments are set to 0. if you supply any arguments, you must supply at least the year, month, and day. you can omit the hours, minutes, seconds, and milliseconds.

The javascript date is measured in milliseconds since midnight 01 January, 1970 UTC. A day holds 86,400,000 milliseconds. the javascript date object range is-100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.

The javascriptDateObject provides uniform behavior implements SS platforms.

The javascriptDateObject supports a number of UTC (universal) methods, as well as local time methods. UTC, also known as Greenwich Mean Time (GMT), refers to the time as set by the World Time Standard. the local time is the time known to the computer where Javascript is executed.

Invoking JavascriptDateIn a non-constructor context (I. e., without the new operator) will return a string representing the current time.

The simhei part is the focus.: The javascript date is measured in milliseconds from the world standard of January 1, 1970 to the present, with 86400000 milliseconds per day. The JS date range is from 100000000 days before January 1, 1970 to 100000000 days after the world standard.

Next let's take a look at Microsoft's description of the javascriptserializer object on msdn, see the link: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

The following is a ing table for. NET and JSON types. For details, see the link above:

The above description. net datetime to JSON format is based on the Javascript standard date, with the number of milliseconds between midnight and the current UTC format date as the conversion result, in this way, we can use the date object built-in functions in JS to convert them to the local format or other formats at will, so that fish Li says, "however, this class has a problem, when serializing the datatime type, the results generated by it will make everyone feel awkward. In fact, the serialization result is still a small problem, writing a conversion function at the front end can solve the problem. "It is not a problem at all, because no conversion function is required at all. The following is the test code:

            DateTime now = DateTime.Now;            Console.WriteLine(now.ToString());            JavaScriptSerializer js = new JavaScriptSerializer();            string json = js.Serialize(now);            Console.WriteLine(json);

The execution result is as follows:

Put the JSON character results in JavaScript and run the following:

The above shows that the serialization result is not a problem in the JS environment. Is there a major problem in the persistence processing? It should be explained by the code of fish Li:

DateTime dt1 = DateTime.Now;JavaScriptSerializer jss = new JavaScriptSerializer();string json = jss.Serialize(dt1);DateTime dt2 = jss.Deserialize<DateTime>(json);context.Response.Write(dt1 == dt2);

The result displayed by the browser is surprising. It turns out to be: false.

In fact, as long as we do not forget to convert to local during deserialization, the problem is solved: (because we are in China's GMT, the UTC time is 8 hours earlier) I replied to fish Li, he replied, "Do you want to stay away?
You want to write General Code. Not only does it process only one datetime type, but you do not know which type has the datetime attribute. What are you going to do ?" This is actually a good solution. If you really want to use the local time, the application will not consider internationalization at all: you can add a string type member to the class containing datetime members. When processing on the web interface, you only need to display the string value of datetime. Even if you use a datetime of the string type completely, it will be OK. If you want to save it to the database, it will be converted back to datetime .. For example:
class Test    {        private DateTime date = DateTime.Now;        /// <summary>        /// Datetime format Date        /// </summary>        public DateTime Date        {            get            {                return date;            }            set            {                date = value;            }        }        /// <summary>        /// String format Date        /// </summary>        public String DateString        {            get            {                return date.ToString();            }        }    }

In fact, the mainstream JSON conversion functions are processed in the same way as the MS database, so I can't think of a so-called general solution that is more standard than the standard, today, I don't have much time to write my Win8 blog client ..

Related Article

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.