chandru chandru - 3 months ago 22
AngularJS Question

convert UTC to local time using angularjs

As a response from the json I am getting the UTC timezone. I need to convert it to local time.

<span class="text-muted">{{trans.txnDate}}</span>


can anyone help on this???

Thanks..

Answer

You could use the date filter to format the date:

<span class="text-muted">{{trans.txnDate | date:'yyyy-MM-dd HH:mm:ss Z' }}</span>

This will output:

2010-10-29 09:10:23 +0530

(assuming trans.txnDate = 1288323623006;)

See this documentation of date in angularjs.org. It has quite a few examples that are very helpful!


EDIT:

In response to your comment, use the following to get the date as 17 oct 2014:

<span class="text-muted">{{trans.txnDate | date:'dd MMM yyyy' | lowercase }}</span>

Check the documentation link that I mentioned above.

EDIT2:

In response to your other comment, use the following code. The problem is that the string that you are getting is not properly formatted so the Date object is not able to recognise it. I have formatted it in the controller and then passed to the view.

function MyCtrl($scope) {
  var dateString = "2014:10:17T18:30:00Z";
  dateString = dateString.replace(/:/, '-'); // replaces first ":" character
  dateString = dateString.replace(/:/, '-'); // replaces second ":" character
  $scope.date = new Date(dateString);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="MyCtrl">
  {{date | date:'dd MMM yyyy' | lowercase }}
</div>

The JS code for replacement can be improved by finding a smarter way to replace the first 2 occurrences of : character.