Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Converting Datetime C# type to Date javascript in asp.net mvc razor application

I have a problem in converting date in javascript . i try this snippet:

$(document).ready(function () {
            var date = new Date();
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();

            $('#calendar').fullCalendar({
                theme: true,
                header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},
                editable: true,
                events: [
                            {
                    title: 'Birthday Party',
                    start: new Date(y, m, d+1, 19, 0),
                    end: new Date(y, m, d+1, 22, 30),
                    allDay: false
                    }
                        ]

                });
            });

and it works, but if i change it to:

 $(document).ready(function () {
            var date = new Date();
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();

            $('#calendar').fullCalendar({
                theme: true,
                header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},
                editable: true,
                events: [
                         @foreach (var m in Model.Get_List_Tache())
                          {
                        @:{ title: "Tache_description", start: new Date(@m.Begin_date.Year +"," + @m.Begin_date.Month +","+ @m.Begin_date.Day ) , end: new Date( @m.End_date.Year +"," [email protected]_date.Month +"," + @m.End_date.Day ) }
                          }
                        ]

                });
            });

There is a syntaxic error in the format of date.

So what is the reason of this error? How can i fix it?

Upvotes: 5

Views: 9558

Answers (3)

Mike
Mike

Reputation: 1673

You can just use c#'s DateTime.ToLongDateString() and pass it into the constructor of the Date object in javascript as long as you want the date as is without modification.

 start: new Date(@m.Begin_date.ToLongDateString());

Upvotes: 1

Vasil Galinovsky
Vasil Galinovsky

Reputation: 334

You can use this solution

start: new Date(@m.Begin_date.ToString("yyyy,MM-1,dd"))

Upvotes: 8

krillgar
krillgar

Reputation: 12805

I'm still with FosterZ, but you should also get rid of the + as well.

So instead of

start: new Date(@m.Begin_date.Year +"," + @m.Begin_date.Month +","+ @m.Begin_date.Day ) ,

try

start: new Date(@m.Begin_date.Year , @m.Begin_date.Month , @m.Begin_date.Day ) ,

If that still doesn't work, then view the source of the page, and see what is being put into the Javascript there. It's most likely not what you're expecting it to be. If you can't figure it out, add that to your question and we can take a look at it.

Upvotes: 2

Related Questions