Swapna
Swapna

Reputation: 403

How to get date time from JavaScript?

I need to get the time from 2017-02-15T09:37:16.087Z. How can I convert it to the general format time stamp? I'm getting time as 2017-02-15T09:37:16.087Z. Here's my code:

<script>
  var app = angular.module('myApp', []);
  app.controller('myCtrl', function ($scope, $http) {
    $http.get('url', {})
    .then(function (response) {
      $scope.names = response.data;
    });
  });
</script>
<div ng-app="myApp" ng-controller="myCtrl" align="center">
  <table>
    <tr>
      <td>device time stamp</td><td>{{names.timestamp}}</td>
    </tr>
  </table>
</div>

Upvotes: 0

Views: 86

Answers (4)

Ankur
Ankur

Reputation: 3199

item.date = $filter('date')(item.date, "dd/MM/yyyy"); // for conversion to string

http://docs.angularjs.org/api/ng.filter:date

This explains how to use date filter to get date-time.

Upvotes: 2

Brian
Brian

Reputation: 2952

If your dates are RFC2822 or ISO 8601 date strings you can use new Date(myDateString) to obtain a native JS Date object set to your date. Your date string looks like an ISO 8601 date so should be right probably for other date formats using JS native methods to parse dates can be inconsistent and unreliable cross-browser.

Once you've got a Date object you can use its .toLocaleString() to convert it to a localized date.

      var app = angular.module('myApp', []);
      app.controller('myCtrl', function ($scope, $http) {
        $http.get('url', {})
        .then(function (response) {
          $scope.names = response.data;
          $scope.names.timestamp = new Date($scope.names.timestamp).toLocaleString(); // Parse the date to a localized string
        });
      });

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse has a lot of info on parsing Date strings.

More info on toLocaleString https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Parsing and formatting dates and times can be a little involved - may be worth considering using Angular's built in methods or momentjs as others have suggested I've simply provided this answer as a starting point for completeness sake for those wanting a native solution.

Upvotes: 1

sda11
sda11

Reputation: 33

Date() function may help

    <script type="text/javascript">
       var dt = Date();
       document.write("Date and Time : " + dt ); 
    </script>

reference

reference2

Upvotes: 1

zoh
zoh

Reputation: 175

Use moment.js library with work date.

http://momentjs.com/docs/

Upvotes: 1

Related Questions