COMMUNITY

Date.getMonth is not a function

In Haxe 4.0.0-rc.3, it appears in JavaScript generated code the date string function is retrieving parts of a date to generate a date string. However, the following generated JavaScript does not work:

// Generated by Haxe 4.0.0-rc.3+e3df7a448
(function ($global) { "use strict";
var HxOverrides = function() { };
HxOverrides.dateStr = function(date) {
	var m = date.getMonth() + 1; // this is where the error is
	var d = date.getDate();
	var h = date.getHours();
	var mi = date.getMinutes();
	var s = date.getSeconds();
	return date.getFullYear() + "-" + (m < 10 ? "0" + m : "" + m) + "-" + (d < 10 ? "0" + d : "" + d) + " " + (h < 10 ? "0" + h : "" + h) + ":" + (mi < 10 ? "0" + mi : "" + mi) + ":" + (s < 10 ? "0" + s : "" + s);
};

The error, of course, is the subject header: date.getMonth is not a function.

In Haxe, this is the code I have while I was recording a tutorial:

get("news", function(content, success)
        {
            if (success)
            {
                var data:Array<shared.TNews> = Json.parse(content);
                if (data.length == 0) return;

                var element = Browser.document.getElementById("content");
                getPage("pages/news-item.htm", function(result)
                {
                    result = result.replace("%title%", data[0].title);
                    result = result.replace("%content%", data[0].content);
                    result = result.replace("%date_posted%", data[0].date_posted.toString()); // this is the line in the callstack which is the source

                    new JQ(element).html(result);
                });
            }
        });

Is this a Haxe-specific issue? I can’t see an Issue on GitHub which would identify this as a Haxe-specific issue but I was wondering if this is fixable my end in case I missed something.

My guess is that the type of date_posted in TNews (probably Date) doesn’t match the type in the json (string or int/float maybe?), which crash at runtime.

When assigning a Json.parse you need to have a 1:1 match of the types (for instance you can’t load map like that).

Oh, I’m being stupid. In the server context, I am putting in the date_posted directly, stringifying the JSON, sending it back to the client and parsing it back into a JSON typedef as above.

It’s probably better to use a String in the typedef and use Date.toString on the server rather than the client.