Skip to content

Instantly share code, notes, and snippets.

@weberste
Last active January 28, 2022 13:47
Show Gist options
  • Save weberste/354a3f0a9ea58e0ea0de to your computer and use it in GitHub Desktop.
Save weberste/354a3f0a9ea58e0ea0de to your computer and use it in GitHub Desktop.
Dates only with Angular-UI Bootstrap datepicker
app.directive('datepickerLocaldate', ['$parse', function ($parse) {
var directive = {
restrict: 'A',
require: ['ngModel'],
link: link
};
return directive;
function link(scope, element, attr, ctrls) {
var ngModelController = ctrls[0];
// called with a JavaScript Date object when picked from the datepicker
ngModelController.$parsers.push(function (viewValue) {
// undo the timezone adjustment we did during the formatting
viewValue.setMinutes(viewValue.getMinutes() - viewValue.getTimezoneOffset());
// we just want a local date in ISO format
return viewValue.toISOString().substring(0, 10);
});
// called with a 'yyyy-mm-dd' string to format
ngModelController.$formatters.push(function (modelValue) {
if (!modelValue) {
return undefined;
}
// date constructor will apply timezone deviations from UTC (i.e. if locale is behind UTC 'dt' will be one day behind)
var dt = new Date(modelValue);
// 'undo' the timezone offset again (so we end up on the original date again)
dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
return dt;
});
}
}]);
Copy link

ghost commented Sep 11, 2015

Great job!

@mkoperator
Copy link

Hi, I found returning the date object from the parser to be more effective as the view stayed the same but without it, data was not marked valid for push back to my service.

So instead of returning:
return viewValue.toISOString().substring(0, 10);
I returned:
return viewValue;

@alvirtuoso
Copy link

I agree with thecrazyrussian using
return viewValue;
I also get invalid date error with the original viewValue.toISOString().substring(0, 10); !

THank you for your good work

@SandeepThomas
Copy link

Updated code to format date in Epoch/Unix Time.

https://gist.github.com/sandeepthomas/78f2de3f0f8f21869f91

@juddey
Copy link

juddey commented Jan 4, 2016

Thanks, this saved me a bunch of time. 👍

@dwietecha
Copy link

Thanks 👏

@shashank1513
Copy link

That is very good post, Thanks !

@deeptinair17
Copy link

The $formatters is not being fired :( and it is setting up my date as undefined , can you pls help?

@pankajparkar
Copy link

Awesome, this saved my day. Thank you so much 💯 👍

@Ultama
Copy link

Ultama commented Aug 19, 2016

Spent a good day trying to get this working, thank you so much!

@billycomic
Copy link

billycomic commented Aug 22, 2016

This COULD save me tons of time. Only thing is, I included the directive in my project and called the attribute on my input, but still getting date modeled as "Sat Jan 01 2000 00:00:00 GMT-0600 (Central Standard Time)" to my scope variable. Am I missing something? I'm using the UI-Bootstrap date picker. Does this directive remove the timestamp or does it just add the time stamp from the location where the user is entering it?

@yogeshp
Copy link

yogeshp commented Apr 14, 2017

Thank you so much!

@amish12
Copy link

amish12 commented Apr 20, 2017

Thanks very helpful!!

@danmdumitru
Copy link

Thanks very helpful!!

@jglogan
Copy link

jglogan commented May 27, 2017

Yessss. Thanks!

@labrego2407
Copy link

Yes! yes! yes! Wonderful man! thank you for sharing!

@cmddavid
Copy link

cmddavid commented Jun 9, 2017

This is awesome! Thanks a lot.

@sandeep2244
Copy link

This is good
But in my case this directive worked in While posting
when i retrive and again without edit post then its not removing timezone

@sabbiryan
Copy link

sabbiryan commented Mar 1, 2018

This is wonderful. It's solved my problem. Thanks

@UlisesVegaBaeza
Copy link

How look it in html ?

@binodtechversant
Copy link

binodtechversant commented Dec 21, 2018

This COULD save me tons of time. Only thing is, I included the directive in my project and called the attribute on my input, but still getting date modeled as "Sat Jan 01 2000 00:00:00 GMT-0600 (Central Standard Time)" to my scope variable. Am I missing something? I'm using the UI-Bootstrap date picker. Does this directive remove the timestamp or does it just add the time stamp from the location where the user is entering it?

It removes the timezone offset from the entered time.

@Macarthurval
Copy link

For those having problems with the returned date as undefined, change the ngModelController.$parsers part:

ngModelController.$parsers.push(function (viewValue) {
    // undo the timezone adjustment we did during the formatting
    viewValue.setMinutes(viewValue.getMinutes() - viewValue.getTimezoneOffset());
    // we just want a local date in ISO format
    var dateString = viewValue.toISOString().substring(0, 10);
    var dateParts = dateString.split("-");
    var newDate = new Date( dateParts[0], parseInt( dateParts[1] )-1, dateParts[2], 0, 0, 0 );
    return newDate;
});

@karenli1995
Copy link

karenli1995 commented May 8, 2020

The above solutions only work for timezones West of the UTC Timezone. Here's a fix that also works for timezones East of UTC so that dates don't appear one day behind:

 app.directive('datepickerLocaldate', ['$parse', function ($parse) {
    var directive = {
        restrict: 'A',
        require: ['ngModel'],
        link: link
    };
    return directive;

    function link(scope, element, attr, ctrls) {
        var ngModelController = ctrls[0];

        // called once user picks a date from datepicker with a JavaScript Date object
        ngModelController.$parsers.push(function (viewValue) {
            // undo the timezone adjustment we did during the formatting
            viewValue.setMinutes(viewValue.getMinutes() - viewValue.getTimezoneOffset());

            // get a local date in ISO format
            var dateString = viewValue.toISOString().substring(0, 10);
            var dateParts = dateString.split("-");
            var newDate = new Date( dateParts[0], parseInt( dateParts[1] )-1, dateParts[2], 0, 0, 0 );

            if (viewValue.getTimezoneOffset() < 0) {
                //case for Timezones East of UTC (floored to account for Indian Standard Time Zone on 30 minute delineations)
                newDate.setHours(newDate.getHours() - Math.floor(newDate.getTimezoneOffset()/60));
            } else {
                //case for Timezones West of UTC
                return newDate;
            }

            return newDate;
        });

        // called once user saves changes on a Title and passes the Date we had picked in the datepicker
        ngModelController.$formatters.push(function (modelValue) {
            if (!modelValue) {
                return undefined;
            }
            // date constructor will apply timezone deviations from UTC (i.e. if locale is West of UTC 'dt' will be one day behind)
            var dt = new Date(modelValue);

            // 'undo' the timezone offset again (so we end up on the original date again)
            if (dt.getTimezoneOffset() < 0) {
                //case for Timezones East of UTC
                dt.setMinutes(dt.getMinutes() - dt.getTimezoneOffset());
            } else {
                //case for Timezones West of UTC
                dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
            }

            return dt;
        });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment