Docs: https://docs.angularjs.org/api/ng/filter/date
Plunker: https://plnkr.co/edit/q6KPNejv52SzewDlvGyu?p=preview
Code snippet below:
var app = angular.module("app", []);
app.controller("ctrl", function($scope, $interval) {
$scope.message = "It works!";
$scope.dateStart = new Date();
$interval(function() {
$scope.dateNow = new Date();
}, 42)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
{{ message }} <br>
{{ dateNow - dateStart | date: 'hh:mm:ss:sss' }} <br>
{{ dateNow - dateStart | date: 'hh:mm:ss:sss' : 'UTC' }} <br>
</div>
- No timezone - displays
01
as hour. - Passing
UTC
as timezone - displays12
as hour.
In my other project I figured this workaround... It feels crap, I don't want to copy-paste crap code. Surely there is a better way?
(maybe I should just use moment, bundle size does not matter that much here)
app.filter('mydate', function(){
return function(text, extra) {
// https://stackoverflow.com/a/39209842/775359
var date = new Date(text)
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
var newdate = new Date(date.getTime() + userTimezoneOffset);
return pad(newdate.getHours(),2) + ":" + pad(newdate.getMinutes(),2) + ":" + pad(newdate.getSeconds(),2)
+ (extra ? ":" + pad(newdate.getMilliseconds(), 3) : "");
};
});
app.filter('pad', [function(){
return function(text, width) {
return pad(text, width)
};
}]);
function pad(text, width) {
text = text + ''; // converting to string because if we pass number it will fail
return text.length >= width ? text : new Array(width - text.length + 1).join('0') + text;
};
Not a solution: AngularJS global Date timezone offset (setting GMT as default still displays it as 12 hours)
Potential duplicate: AngularJs filter date adding 2 hours (not answered)