Search code examples
javascriptjqueryjquery-uiformatdatetime

Formatting date with JavaScript in a customer fronting e-commerce application


We have a situation where in we need to format a json response attribute which contains a date string (say "2017-01-29"). To format the date we are currently using jquery UI function like:

dayVar = $.datepicker.formatDate('M dd, yy', new Date("2017-01-29"));

But if we print dayVar, it is displayed as Jan 28, 17 as against the expected Jan 29, 17. What is the best solution to fix this so that it can fit into any time zone?

It is single page application built with Marionette framework.


Solution

  • When instantiating your new Date object, you are leaving the Time up to interpretation. By default most environments will interpret this to 00:00:00 ... however, as this is javascript you are at the mercy of the user's local machine to interpret this value.

    I would append the 00:00:00 in the string to the Date() function. to enforce the expected outcome, or even attempt to play with the time to see what kind of outputs it creates (Maybe set it for 1AM or 22:00:00) this should provide a more in depth understanding of what is causing the issue, and hopefully the solution.