2

I'm doing something that should be really simple: I'm getting a string that represents an expiration date and using JavaScript to determine whether or not the expiration date has come to pass. My approach has been as follows:

var dateStringFromJson = "2015-09-11T11:21:48.113";
var expirationDate = new Date(Date.parse(dateStringFromJson));
if (expirationDate > new Date()) {
    // Expiration not up
}

If I executed this function at a time before the expiration, say 10:50am, the comparison would fail and the function would act as if the expiration date was up.

I'm confident this problem has to do with JavaScript's timezone conversion. I'm in UTC-7 but my customers may be in any time zone across the U.S., so timezone specific fixes will not work here. I'd also prefer not to add an external library like moment.js to the project unless absolutely necessary.

2 Answers2

2

You can parse the date manually if its format is consistent:

var DATE_STRING = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})$/;
var match = DATE_STRING.exec(dateStringFromJson);

var expirationDate = new Date();
expirationDate.setFullYear(+match[1]);
expirationDate.setMonth(+match[2] - 1);
expirationDate.setDate(+match[3]);
expirationDate.setHours(+match[4]);
expirationDate.setMinutes(+match[5]);
expirationDate.setSeconds(+match[6]);
expirationDate.setMilliseconds(+match[7]);

Consider just putting the timestamp in UTC, though, which is how it’s parsed. (And add a Z to the end to indicate that.)

Ry-
  • 218,210
  • 55
  • 464
  • 476
2

Use a function to localize the json string. When you parse a date string without a time zone, it assumes it is in UTC. See my answer to a similar question for an explanation of how the localizeDateStr() function works.

function localizeDateStr(date_to_convert_str) {
  var date_to_convert = new Date(date_to_convert_str);
  var local_date = new Date();
  date_to_convert.setHours(date_to_convert.getHours() + (local_date.getTimezoneOffset() / 60));
  return date_to_convert;
}

function checkExpired() {
  var dateString = document.getElementById('date').value;
  var expirationDate = localizeDateStr(dateString);
  if (expirationDate > new Date()) {
    alert("Expiration not up.");
  } else {
    alert("Expired!");
  }
}
Expiration Datetime:
<input id="date" type="text" value="2015-09-11T11:21:48.113" />
<button id="btn" onclick="checkExpired()">Is expired?</button>
Community
  • 1
  • 1
Andrew Mairose
  • 10,615
  • 12
  • 60
  • 102