nikhilk / scriptsharp

Script# Project - a C# to JavaScript compiler, to power your HTML5 and Node.js web development.
http://scriptsharp.com
Other
658 stars 182 forks source link

Date.Formating - 0.8 #256

Open andrewharry opened 12 years ago

andrewharry commented 12 years ago

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));
        }
nikhilk commented 12 years ago

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.

andrewharry commented 12 years ago

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

michaelaird commented 12 years ago

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);
            }
        }