LS2
LS2

Reputation: 152

DatePicker Error in Angular JS due to UTC

I have selected the 12th of September 2014 in the UI.

Following is the code

    ctrl.$formatters.push(function (modelValue) {
            console.log(modelValue);
            var dt = new Date(modelValue);
            dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
            console.log(dt)
            return dt;
        });

The two console logs i see are the following.

  1. 09/11/2014
  2. Wed Sep 10 2014 18:30:00 GMT+0530 (IST)

Am not sure why the conversion from UTC to local is not carried out correctly.

Thanks in advance.

Upvotes: 0

Views: 163

Answers (1)

Ralph
Ralph

Reputation: 305

Its not clear what you are trying to do. The input does not have a time. Do you want to add the current time of the day to the arbitrary date? Or do you just want a local representation of the date? I'm geussing the latter.

Instead of dt.setMinutes(...) and the following two lines, replace all three lines with:

return dt.toLocaleDateString();

If you ARE trying to set the time to now on whatever date is input (I don't know why...) but you might try:

dt.setTime( new Date().getTime() );

instead of the setMinutes(...) line.

then you can return dt.toLocaleString;

All date objects are stored as miliseconds since, like 1972. It is best to use the built in Date object methods to get what you want from it. Here are the docs for reference.

Upvotes: 1

Related Questions