scriptsharp icon indicating copy to clipboard operation
scriptsharp copied to clipboard

Date.Formating - 0.8

Open andrewharry opened this issue 12 years ago • 3 comments

I am struggling to get the string.format to work with date formats

I have stepped through the code and it appears that the constructor for my date object doesn't have a 'name' field and the constructor has a prototype called 'invalid date'

The date has been passed in by json from my server. I transform this into a javascript date object with the code below

        internal static Date FixDate(Date date) {
            if (Script.IsNullOrUndefined(date)) return null;
            if (date.ToString().IndexOf("Date") > -1)
                return new Date(int.Parse(date.ToString().Substr(6)));
            return date;
        }

And I am using the next piece for formatting the date

        internal static int ToYearMonthKey(Date date) {
            if (Script.IsNullOrUndefined(date)) return 0;
            return int.Parse(string.Format(CultureInfo.InvariantCulture, "{0:yyyyMM}", date));
        }

andrewharry avatar Oct 08 '12 10:10 andrewharry

Looks like constructor.name doesn't work in IE... but does in chrome... and it is surfacing now since the script# runtime is no longer touching those native objects to add such things as it used to. Will find another way to fix the detection inside the string formatting functionality.

In your FixDate method, I imagine the parameter value is actually a string and not a Date if you're getting it from JSON.

As far as the formatting itself goes, that format works fine me - verified via this script:

ss.format(ss.culture.neutral, "{0:yyyyMM}", new Date()));

Probably will work once the constructor name thing is resolved.

nikhilk avatar Oct 08 '12 17:10 nikhilk

Yeah it is the ASP.net MVC json date format = "/Date(1239018869048)/" Not sure if that is changing in MVC 4 as they are switching json.net from their own serialiser.

Wishing I didn't upgrade to windows 8 now. Silly IE10 screws up all sorts of ajax posting including adding comments in github + stackoverflow

andrewharry avatar Oct 08 '12 22:10 andrewharry

This might be helpful. Here's my function for parsing that style of date:

        public static Date ParseJsonDate(string input)
        {
            if (String.IsNullOrEmpty(input))
            {
                return null;
            }

            Number milliseconds = Number.Parse(input.ReplaceRegex(new RegularExpression(@"\/Date\((-?\d+)\)\/".Unescape()), "$1"));
            if (Number.IsNaN(milliseconds))
            {
                return null;
            }
            else
            {
                return new Date(milliseconds);
            }
        }

michaelaird avatar Oct 09 '12 00:10 michaelaird