Mabeh Al-Zuq Yadeek
Mabeh Al-Zuq Yadeek

Reputation: 84

Can anyone explain why my date function is giving me a wrong conversion via JS date object?

Sorry for the title if it doesn't explain my problem too well.

I'm having a weird problem in my script where in the initial stage, I convert a date string into milliseconds and then later on in the script, it is converted back to a legible date format. The date strings that give me problems are the ones that have the regular date, but also have the hour attached to it as well. Here's an example:

legitDate = function (date) {

    var months = ['01', '02', '03', '04', '05', '06',
                  '07', '08', '09', '10', '11', '12'];

    return months[date.getUTCMonth()] + "/" + date.getUTCDate() + "/" + date.getUTCFullYear()
}

var init = Date.parse("1/27/2016  7:00:00 PM");
var ayy = new Date(init);
var result = legitDate(ayy);

The finial result reads 1/28/2016, instead of the original 1/27/2016. I have no idea why this conversion is happening the way it's happening.

Upvotes: 0

Views: 105

Answers (2)

RobG
RobG

Reputation: 147363

Do not use the Date constructor (or Date.parse, they do the same thing) to parse strings. The only format specified in ECMA-262 is a subset of ISO 8601, and that is not supported by all browsers in use and in some places the two are inconsistent. The format in the OP is not consistent with ISO 8601, therefore parsing is entirely implementation dependent.

Always manually parse strings. A library can help, but it's not hard to write a parser for a particular format.

To parse a string like "1/27/2016 7:00:00 PM" based on the host timezone offset (i.e. "local"), consider the following which treats missing values as zero and validates the resulting Date:

// Parse string in 1/27/2016  7:00:00 PM format
// Missing time values are treated as zero
// If any value is invalid, returns an invalid date (time value NaN)
function parseDate(s) {
  var b = s.match(/\d+/g) || [];
  var hr = (/pm\s*/.test(s)? 12 :0) + (+b[3] || 0);
  var d = new Date(b[2], --b[0], b[1], hr, (b[4]||0), (b[5]||0));

  // Validate the generated date against input values
  return d && d.getMonth() == b[0] && (b[3] || 0) < 13 &&
         d.getMinutes() == (b[4] || 0)? d : new Date(NaN);
}

['1/27/2016  7:00:00 PM',
 '2/29/2016 12:45:15 am',
 '6/31/2016 12:45:15 am', // invalid date
 '2/29/2016 13:45:15 am', // invalid hours
 '2/29/2016 06:45am'    , // missing seconds
 '2/29/2016'              // missing time asssumed as 00:00:00
].forEach(function(s) {
  document.write(parseDate(s) + '<br>');
});

Upvotes: 1

display name
display name

Reputation: 4185

Try change and specify UTC

var init = Date.parse("1/27/2016  7:00:00 PM UTC");

Upvotes: 0

Related Questions