Achintha Samindika
Achintha Samindika

Reputation: 1954

JavaScript return time is not correct

I'm developing mobile application and to construct the date object I'm using following date string. But the time string which I need to out put is strange than the input time.

Input time:

2014-01-09T20:40:00

Output time:

  10th January, 2:10am 

To Constuct the date object I'm using following code

var date = new Date('2014-01-09T20:40:00');

Dates.getAMPMTimeFromDateObject = function (date) {
            var dateSuffix = Constants.Formatting.DateAMSuffix,
                hours = date.getHours(),
                minutes = date.getMinutes(),
                minutesString;

            hours = (hours + 24) % 24;

            if (hours === 0) {
                hours = 12;
            } else if (hours > 12) {
                hours = hours % 12;
                dateSuffix = Constants.Formatting.DatePMSuffix;
            } else if (hours === 12) { //This is specific fix for 12PM exceptional case
                dateSuffix = Constants.Formatting.DatePMSuffix;
            }

            minutesString = (minutes < 10) ? '0' + minutes : minutes;

            return hours + ':' + minutesString + dateSuffix;
        };

Upvotes: 1

Views: 1131

Answers (2)

Jeremy
Jeremy

Reputation: 2709

You absolutely need to specify the time-zone for ISO date strings. This is a cross-browser compatibility issue.

If you don't specify a time-zone:

  • Chrome assumes your input is UTC
  • Firefox / IE assume your input is local

A quick fix would be to explicitly use UTC:

var date = new Date('2014-01-09T20:40:00Z'); //note 'Z' for "zero-offset"

However, older browsers don't even understand ISO date/time inputs, so use this with caution.

A handy reference for date/time string compatibility: http://blog.dygraphs.com/2012/03/javascript-and-dates-what-mess.html

Upvotes: 1

ColinE
ColinE

Reputation: 70142

Your issue is most likely due to timezones. Are you located in a country with a half-hour timezone offset?

Your output time is clearly formatted using your current locale.

In other words, there is nothing wrong with your date! You need to consider how you handle timeszones in your code.

As a rule, ensure your dates are GMT within your code, use the ISO date/time format when parsing / serializing dates, and only convert dates to a specific timezone when displaying to the user.

Upvotes: 2

Related Questions