Jürgen Bayer
Jürgen Bayer

Reputation: 3023

How to handle dates correctly that are send to the server and back

I just learned that the JavaScript Date object apparently always stores the local time zone offset. When posting such a date to the server (using $http.post for example) the server gets the UTC date (local date minus time zone offset). That of course is right. In my case the server stores the date in a database.

When getting dates from the server (using $http.get for example) the server sends back the UTC date. If I directly bind these dates to a view the view displays the wrong date (the UTC date). To avoid that I found out that I must write a new Date instance to the model, passing the date I got from the server.

Problem is that this is a lot of work, especially if the server sends a model that actually should be directly bound to the view.

I am looking for a way to avoid having to create Date instances for each date property of models I got from the server in my controllers.

Upvotes: 3

Views: 1402

Answers (1)

gbro3n
gbro3n

Reputation: 6967

I have created this function that can be ran on the client, which adjusts the date by the current timezone offset. When the adjusted date is sent to the server, the DateTime object parsed from the post data will represent the same (local) date as seen on the client UI:

        adjustDateByTimezoneOffset: function (date) {

            // Javascript Date object stores the local timezone offset.
            // On tranmission to the server the UTC date is sent. The server 
            // may not be timezone aware, and so this function facilitates
            // adjusting to a date which can then be sent to a .NET web application and
            // be recieved as a DateTime instance that equals the current (local) time on 
            // the client.

            if (date && (date instanceof Date)) {

                var timezoneOffsetMinutes = date.getTimezoneOffset();

                var setMinutes = date.getMinutes() - timezoneOffsetMinutes;

                date.setMinutes(setMinutes);
            }
            else {

                throw "Input variable must be Date";
            }

            return date;
        }

Upvotes: 1

Related Questions