简体   繁体   中英

AngularJS custom filter not working on iOS and IE

I have created the following filter to convert MySQL dates and adjust time for the timezone relatively to UTC.

angular.module('HIS')
    .filter('dateToISO', function () {
        return function (input) {
            var offset = new Date().getTimezoneOffset();
            var date = new Date(input);
            date.setTime(date.getTime()-offset*60000);
            return date.toISOString();
        };
    });

Then, I use the filter to convert dates to my preferred format and show them inside HTML as follows. (I have changed the Angular interpolation tags to [[ ]] to avoid conflicts with Laravel's blade syntax {{ }} )

[[prescription.patient.first_name]] [[prescription.patient.last_name]]<br>
[[prescription.created_at | dateToISO | date:"EEEE, d/M/yy h:mm a"]]

This works fine with all the desktop browsers except for IE . Also this do not work for browsers in iOS (Safari/Chrome).

Working on desktop browsers except IE

在IE以外的桌面浏览器上的工作示例

Not working on iOS browsers and IE. The raw angular code is shown instead.

在iOS浏览器上不起作用

Important :

When I was searching, I found that the problem with IE was solved in Angular v1.3.3 and above. But I'm using v1.5.5 and still the problem is there. There was no clue on the Internet about this situation on iOS browsers. Can anyone explain why this happen and how to solve this?

Thanks in advance!

I finally found the cause to the problem. I had used var date = new Date(input); where input is in the format Ymd H:i:s which is a MySQL timestamp.

JavaScript use Date.parse when creating a Date object from a timestamp. In desktop versions of many browsers, they accept MySQL timestamps to create Date objects. But in iOS and IE, this doesn't work. For date to be created using a string, the timestamp should be in the ISO format. Therefore, it do not accept MySQL timestamps.

To solve this, I referred this question where the timestamp was split and then used to create the date object.

angular.module('HIS')
    .filter('dateToISO', function () {
        return function (input) {
            var t = input.split(/[- :]/);
            var date = new Date(Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]));
            return date;
        };
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM