0

The built-in Angular date filter takes a json string as an input, looks for timezone data (via a regex) and then returns a date object in UTC time. All good - and I understand the need to store dates on the server in UTC.

I have a situation where I am just storing the date part (without timezone information) and I do not want that date converted to UTC ("2013-06-30T00:00:00.000" is the date string returned from the server - and it is rendering as 2013-06-29 - which is correct, because my locale is GMT-0400 (Eastern Daylight Time)).

I'd like to create a custom date filter that overrides Angular's existing date filter, so instead of using:

date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));

From lines 10131-10132 (in v1.0.7), I want it to use:

date.setFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));

I would like to be able to leverage all of the other parts of the filter (regex, formatting, etc.). I obviously do not want to change the native implementation as that would have a lot of undesired consequences in areas where I need UTC conversion.

Any assistance would be greatly appreciated.

Update: per @pkozlowski.opensource, I updated to 1.1.5 (by hand, Nuget only has 1.07) and it works as desired. Interestingly, here is the new implementation:

function jsonStringToDate(string) {
  var match;
  if (match = string.match(R_ISO8601_STR)) {
  var date = new Date(0),
      tzHour = 0,
      tzMin  = 0,
      dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
      timeSetter = match[8] ? date.setUTCHours : date.setHours;

    if (match[9]) {
      tzHour = int(match[9] + match[10]);
      tzMin = int(match[9] + match[11]);
    }
    dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
    var h = int(match[4]||0) - tzHour;
    var m = int(match[5]||0) - tzMin
    var s = int(match[6]||0);
    var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
    timeSetter.call(date, h, m, s, ms);
    return date;
  }
  return string;
}

If match[8] (Timezone information) is undefined, it calls setFull[Year|Hours] instead of setUTCFull[Year|Hours]. Very nice.

4

1 回答 1

1

I think that it was fixed in the unstable branch, check with 1.1.5 where dates (as string) are interpreted in the local time zone instead of UTC.

于 2013-06-30T15:24:35.860 回答