How do I format a Microsoft JSON date?

后端 未结 30 3060
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 04:48

I\'m taking my first crack at Ajax with jQuery. I\'m getting my data onto my page, but I\'m having some trouble with the JSON data that is returned for Date data types. Basi

相关标签:
30条回答
  • 2020-11-21 04:55
    var newDate = dateFormat(jsonDate, "mm/dd/yyyy"); 
    

    Is there another option without using the jQuery library?

    0 讨论(0)
  • 2020-11-21 04:57

    A late post, but for those who searched this post.

    Imagine this:

        [Authorize(Roles = "Administrator")]
        [Authorize(Roles = "Director")]
        [Authorize(Roles = "Human Resources")]
        [HttpGet]
        public ActionResult GetUserData(string UserIdGuidKey)
        {
            if (UserIdGuidKey!= null)
            {
                var guidUserId = new Guid(UserIdGuidKey);
                var memuser = Membership.GetUser(guidUserId);
                var profileuser = Profile.GetUserProfile(memuser.UserName);
                var list = new {
                                  UserName = memuser.UserName,
                                  Email = memuser.Email ,
                                  IsApproved = memuser.IsApproved.ToString() ,
                                  IsLockedOut = memuser.IsLockedOut.ToString() ,
                                  LastLockoutDate = memuser.LastLockoutDate.ToString() ,
                                  CreationDate = memuser.CreationDate.ToString() ,
                                  LastLoginDate = memuser.LastLoginDate.ToString() ,
                                  LastActivityDate = memuser.LastActivityDate.ToString() ,
                                  LastPasswordChangedDate = memuser.LastPasswordChangedDate.ToString() ,
                                  IsOnline = memuser.IsOnline.ToString() ,
                                  FirstName = profileuser.FirstName ,
                                  LastName = profileuser.LastName ,
                                  NickName = profileuser.NickName ,
                                  BirthDate = profileuser.BirthDate.ToString() ,
                };
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            return Redirect("Index");
        }
    

    As you can see, I'm utilizing C# 3.0's feature for creating the "Auto" Generics. It's a bit lazy, but I like it and it works. Just a note: Profile is a custom class I've created for my web application project.

    0 讨论(0)
  • 2020-11-21 04:58

    There is no built in date type in JSON. This looks like the number of seconds / milliseconds from some epoch. If you know the epoch you can create the date by adding on the right amount of time.

    0 讨论(0)
  • 2020-11-21 05:00

    Updated

    We have an internal UI library that has to cope with both Microsoft's ASP.NET built-in JSON format, like /Date(msecs)/, asked about here originally, and most JSON's date format including JSON.NET's, like 2014-06-22T00:00:00.0. In addition we need to cope with oldIE's inability to cope with anything but 3 decimal places.

    We first detect what kind of date we're consuming, parse it into a normal JavaScript Date object, then format that out.

    1) Detect Microsoft Date format

    // Handling of Microsoft AJAX Dates, formatted like '/Date(01238329348239)/'
    function looksLikeMSDate(s) {
        return /^\/Date\(/.test(s);
    }
    

    2) Detect ISO date format

    var isoDateRegex = /^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(\.\d\d?\d?)?([\+-]\d\d:\d\d|Z)?$/;
    
    function looksLikeIsoDate(s) {
        return isoDateRegex.test(s);
    }
    

    3) Parse MS date format:

    function parseMSDate(s) {
        // Jump forward past the /Date(, parseInt handles the rest
        return new Date(parseInt(s.substr(6)));
    }
    

    4) Parse ISO date format.

    We do at least have a way to be sure that we're dealing with standard ISO dates or ISO dates modified to always have three millisecond places (see above), so the code is different depending on the environment.

    4a) Parse standard ISO Date format, cope with oldIE's issues:

    function parseIsoDate(s) {
        var m = isoDateRegex.exec(s);
    
        // Is this UTC, offset, or undefined? Treat undefined as UTC.
        if (m.length == 7 ||                // Just the y-m-dTh:m:s, no ms, no tz offset - assume UTC
            (m.length > 7 && (
                !m[7] ||                    // Array came back length 9 with undefined for 7 and 8
                m[7].charAt(0) != '.' ||    // ms portion, no tz offset, or no ms portion, Z
                !m[8] ||                    // ms portion, no tz offset
                m[8] == 'Z'))) {            // ms portion and Z
            // JavaScript's weirdo date handling expects just the months to be 0-based, as in 0-11, not 1-12 - the rest are as you expect in dates.
            var d = new Date(Date.UTC(m[1], m[2]-1, m[3], m[4], m[5], m[6]));
        } else {
            // local
            var d = new Date(m[1], m[2]-1, m[3], m[4], m[5], m[6]);
        }
    
        return d;
    }
    

    4b) Parse ISO format with a fixed three millisecond decimal places - much easier:

    function parseIsoDate(s) {
        return new Date(s);
    }
    

    5) Format it:

    function hasTime(d) {
        return !!(d.getUTCHours() || d.getUTCMinutes() || d.getUTCSeconds());
    }
    
    function zeroFill(n) {
        if ((n + '').length == 1)
            return '0' + n;
    
        return n;
    }
    
    function formatDate(d) {
        if (hasTime(d)) {
            var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
            s += ' ' + d.getHours() + ':' + zeroFill(d.getMinutes()) + ':' + zeroFill(d.getSeconds());
        } else {
            var s = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
        }
    
        return s;
    }
    

    6) Tie it all together:

    function parseDate(s) {
        var d;
        if (looksLikeMSDate(s))
            d = parseMSDate(s);
        else if (looksLikeIsoDate(s))
            d = parseIsoDate(s);
        else
            return null;
    
        return formatDate(d);
    }
    

    The below old answer is useful for tying this date formatting into jQuery's own JSON parsing so you get Date objects instead of strings, or if you're still stuck in jQuery <1.5 somehow.

    Old Answer

    If you're using jQuery 1.4's Ajax function with ASP.NET MVC, you can turn all DateTime properties into Date objects with:

    // Once
    jQuery.parseJSON = function(d) {return eval('(' + d + ')');};
    
    $.ajax({
        ...
        dataFilter: function(d) {
            return d.replace(/"\\\/(Date\(-?\d+\))\\\/"/g, 'new $1');
        },
        ...
    });
    

    In jQuery 1.5 you can avoid overriding the parseJSON method globally by using the converters option in the Ajax call.

    http://api.jquery.com/jQuery.ajax/

    Unfortunately you have to switch to the older eval route in order to get Dates to parse globally in-place - otherwise you need to convert them on a more case-by-case basis post-parse.

    0 讨论(0)
  • 2020-11-21 05:00

    I also had to search for a solution to this problem and eventually I came across moment.js which is a nice library that can parse this date format and many more.

    var d = moment(yourdatestring)
    

    It saved some headache for me so I thought I'd share it with you. :)
    You can find some more info about it here: http://momentjs.com/

    0 讨论(0)
  • 2020-11-21 05:00
    var obj = eval('(' + "{Date: \/Date(1278903921551)\/}".replace(/\/Date\((\d+)\)\//gi, "new Date($1)") + ')');
    var dateValue = obj["Date"];
    
    0 讨论(0)
提交回复
热议问题