Search code examples
javascriptc#momentjsutc

Time not getting converted to local time properly via moment.js


11-06-2015 12:44:30 

My datetime has the above format however it isn't getting converted to Local Time it gives me the month as November instead.

var check = moment('@Model.Invoice.InvoiceDate').format('YYYY-MM-DD HH:mm:ss');

                    var localTime = moment.utc(check).toDate();
                    localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');

                    console.log(localTime);

White saving i am using DateTime.UTCNow function of C# and while getting the data i am using the following code.

Code:

 var formatDate = new Date('@Model.Invoice.InvoiceDate.ToLocalTime()');
                    console.log(formatDate);
                    formatDate = moment.utc(formatDate).toDate();
                    console.log(formatDate);
                    var dateTime = moment(formatDate).format('lll');
                    console.log(dateTime);

Example of what is happening:

  var formatDate = new Date('Sat Jun 13 2015 13:00:11 GMT+0530 (India Standard Time)');
                            console.log(formatDate);
                            formatDate = moment.utc(formatDate).toDate();
                            console.log(formatDate);
                            var dateTime = moment(formatDate).format('lll');
                            console.log(dateTime);

Solution

  • You can print an UTC ISO 8601 date for moment with ToString("s") but it will lack the Z, so you need to add it yourself.

    var localTime = moment('@String.concat(Model.Invoice.InvoiceDate.ToString("s"), "Z")').format('lll');

    Or by adding the Z on client side :

    var localTime = moment('@Model.Invoice.InvoiceDate.ToString("s")' + 'Z').format('lll');