1

I'm trying to push a C# DateTime to a javascript array. Ideally, I'd like it converted to a string. I've tried multiple different approaches but none have worked. The continual error I get is that I'm missing a ) which I can't make much sense of.

I declare a local js variable to hold the values:

var startDates = [];

I've tried:

        @foreach (var d in Model.Items)
        {
            @:startDates.push(Date(@d.StartDate.Date));
        }

and

        @foreach (var d in Model.Items)
        {
            @:startDates.push(Date(@d.StartDate));
        }

and

        @foreach (var d in Model.Items)
        {
            @:startDates.push(@d.StartDate);
        }

and

        @foreach (var d in Model.Items)
        {
            @:startDates.push(Date(@d.StartDate.ToString()));
        }

and

        @foreach (var d in Model.Items)
        {
            @:startDates.push(new Date(@d.StartDate.Date));
        }

and

        @foreach (var d in Model.Items)
        {
            var date = d.StartDate.ToString();
            @:startDates.push(date);
        }

each results in the same JavaScript runtime error: I'm missing a ).

I'm also using a similar method for floats that works just fine:

        @foreach (var v in Model.Items)
        {
            @:values.push(parseFloat(@v.Value));
        }

An example of the rendered JavaScript is:

            startDates.push(new Date(1/1/2016 12:00:00 AM));
            startDates.push(new Date(2/1/2016 12:00:00 AM));
            startDates.push(new Date(3/1/2016 12:00:00 AM));
            startDates.push(new Date(4/1/2016 12:00:00 AM));
            startDates.push(new Date(5/1/2016 12:00:00 AM));
            startDates.push(new Date(6/1/2016 12:00:00 AM));
coolhand
  • 1,876
  • 5
  • 25
  • 46

1 Answers1

1

The error is being caused by the value passed into the new Date() constructor.

It should have quotes around the date value: new Date('1/1/2016 12:00:00 AM')

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Kevin Boucher
  • 16,426
  • 3
  • 48
  • 55
  • This works. Is there a way to parse the `Date` to a short date (i.e. no time)? I tried `@:startDates.push(new Date('@d.StartDate.Date'));` but this still renders the long date format – coolhand Apr 27 '18 at 21:22
  • Indeed it needs quotes, but even then it may not work depending on your visitors timezone. See here for a foolproof way: https://stackoverflow.com/a/22835394/1220550 – Peter B Apr 27 '18 at 21:23
  • 1
    IMHO it's unfortunate Date wasn't named DateTime. When strings are parsed they're assumed to be UTC which can lead to confusion. From the [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) you can also specify local date using ```new Date(year, month, day)```, but beware month is zero based (which is also unintuitive). – Mark G Apr 27 '18 at 23:06