Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 749
Jürgen Bayer Avatar asked Nov 29 '25 18:11

Jürgen Bayer


1 Answers

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;
        }
like image 51
gb2d Avatar answered Dec 01 '25 11:12

gb2d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!