2017-02-15 120 views
0

我需要从2017-02-15T09:37:16.087Z得到时间。我如何将它转换为通用格式时间戳?我得到的时间为2017-02-15T09:37:16.087Z。这是我的代码:如何从JavaScript获取日期时间?

<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> 

回答

1

如果您的日期是RFC2822或ISO 8601个日期字符串可以使用new Date(myDateString)获取设置为本地JS Date对象你的约会。你的日期字符串看起来像一个ISO 8601日期,所以应该是正确的可能为其他日期格式使用JS本地方法来解析日期可以是不一致的和不可靠的跨浏览器。

一旦你有一个Date对象,你可以使用它的.toLocaleString()将它转换为本地化的日期。

 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有很多关于解析日期字符串的信息。

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

解析和格式化日期和时间

更多信息,可以是一个有点棘手 - 可能是值得采用了棱角分明的内置方法或momentjs考虑如其他人所说,我只是提供这个答案为出发对于那些想要一个本地解决方案的人来说,为了完整起见。

+0

非常感谢你@brian – Swapna

1

日期()函数可以帮助

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

reference

reference2