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

3.6k views Asked by At
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);
2

There are 2 answers

6
Pierre Inglebert On BEST ANSWER

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

2
yogi On

Try this

var check = moment('11-06-2015 12:44:30', 'DD-MM-YYYY HH:mm:ss')
                    .format('YYYY-MM-DD HH:mm:ss');

or in your case this

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

instead of

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

While giving moments a date string you need to specify which part is what.