1

I have a JQuery function like this

function (){
           alert($scope.modal.ondutytime);

            var data = {
                        "OnDutyTime": $scope.modal.ondutytime,
                        "Comments": ""
                       };

            alert(JSON.stringify(data));
}

The $scope contains all the values which I set in angularJs view. The problem is that the first alert shows local ondutytime date & time as

Tue Oct 06 2015 20:30:44 GMT+0500 (Pakistan Standard Time)

but when I create a JSON object data and then alert it after stringify, it shows UTC date & time (5 hours difference)

{
    "OnDutyTime": "2015-10-06T15:33:10.903Z"
    "comments":""
}

How can I ensure that it do not convert to GMT?

EDIT: I also tried this

new Date('2015-10-06T15:33:10.903Z') 

it is showing me local date & time, however I have to supply it $scope.modal.ondutytime which already contains my local date & time. So when I write the above line as

new Date($scope.modal.ondutytime) 

it again shows UTC date & time.

liaqat ali
  • 11
  • 3
  • it is setting proper `iso string`, pass that into `new Date()` and alert ...will be the same as the first. Try `new Date().toJSON()` in your console and `new Date().toISOString()` .. will be same – charlietfl Oct 06 '15 at 15:53
  • `new Date($scope.modal.ondutytime).toJSON()` it also converts to UTC but I don't need any other date. I need local date. – liaqat ali Oct 06 '15 at 16:26
  • it's not UTC it's an iso date. What format are you looking for? – charlietfl Oct 06 '15 at 16:28
  • I want format local for Pakistan, that is `GMT+0500`. – liaqat ali Oct 06 '15 at 16:33
  • did you even try `alert(new Date('2015-10-06T15:33:10.903Z'))`? It's the same thing – charlietfl Oct 06 '15 at 16:35
  • `new Date($scope.modal.ondutytime).toString()` it solved my issue, thanks for your help, you guided me towards that. Post it as answer please. – liaqat ali Oct 06 '15 at 16:42
  • @liaqatali - The output of `toString` is highly implementation dependent. It doesn't belong in JSON. You should use ISO. If you want ISO as local time with offset, then see http://stackoverflow.com/a/31104671/634824 – Matt Johnson-Pint Oct 06 '15 at 17:24

1 Answers1

0

I had the same issue while dealing with brazilian timezone (GMT-3) and trying to save a "new Date()" at localstorage. The solution that I found was to change the prototype of javascript "Date()" to make the browser's timezone as javascript's default. Of course that is not a very good thing to do, but depending of what are you needs, it may help.

You can find the code that I used here.

As you'll see, this Stackoverflow's question has more than one solution for this problem, including the use of the "Moment JS", which is a very popular library for handling time.