Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use always UTC+0 - Fix custom timezone on client browser with javascript / angularjs

How can I fix a custom timezone on client browser with javascript ?

For example, on angular I have a date "2015-10-16T00:00:00.000Z" from a backoffice.

I would like to have a display (with UTC-4 New York or with UTC+2 France), always : 16/10/2015

Read :

If I use the UTC on New York, I have : 15/10/2015.

<p ng-bind="(myDate | date:'dd/MM/yyyy')"></p>

Write :

I modified the date prototype toJSON to delete timezone :

// Remove TimeZone
Date.prototype.toJSON = function(){
    return moment(this).format('YYYY-MM-DD') + 'T00:00:00.000Z';
};
like image 611
Jérémie Chazelle Avatar asked Nov 09 '22 03:11

Jérémie Chazelle


1 Answers

I added this :

// Add timeZone
Date.prototype.addTimeZone = function () {
    if(this.getTimezoneOffset() > 0){
        this.setMinutes(this.getTimezoneOffset());
    }

    return this;
};

And this on my controller/model :

    new Date(myDate).addTimeZone();

To resume :

extend-date-prototype.js

// Add timeZone
Date.prototype.addTimeZone = function () {
    if(this.getTimezoneOffset() > 0){
        this.setMinutes(this.getTimezoneOffset());
    }

    return this;
};

// Remove TimeZone
Date.prototype.toJSON = function(){
    return moment(this).format('YYYY-MM-DD') + 'T00:00:00.000Z';
};

view.html

<p ng-bind="(myDate | date:'dd/MM/yyyy')"></p>

controller.js

new Date(myDate).addTimeZone();

I use moment.js

like image 70
Jérémie Chazelle Avatar answered Nov 14 '22 23:11

Jérémie Chazelle