Auto-updatable values in angularJS - javascript

I have array of dates $scope.dates = [] ($scope.dates[0].date). I need to create another array with auto-updateble(!) values of durations.
$scope.dates[i].duration = Date.now() - $scope.dates[i].date.
I want to create timer in seconds:
<tr ng-repeat="x in dates">
<td>{{x.date | date:'HH:mm:ss'}}</td>
<td>{{x.duration}}</td>
Edit: Probled solved

Call this function, it will maintain object in $rootScope object:
$rootScope.timerActivate = function () {
console.log('activateTimer ::');
if(!$rootScope.time)
{
$rootScope.time = {}
}
var countDown = function () {
var today = new Date();
var hours = new Date().getHours();
var hours = (hours + 24) % 24;
var mid = 'am';
if (hours == 0) { //At 00 hours we need to show 12 am
hours = 12;
}
else if (hours > 12)
{
hours = hours % 12;
mid = 'pm';
}
var minute = today.getMinutes();
var sec = today.getSeconds();
$rootScope.time.hours = (hours < 10) ? '0' + hours : hours;
$rootScope.time.minutes = (minute < 10) ? '0' + minute : minute;
$rootScope.time.seconds = (sec < 10) ? '0' + sec : sec;
$rootScope.time.blink = (sec % 2) ? ':' : ' ';
$rootScope.time.mid = mid;
$timeout(countDown, 1000);
};
$timeout(countDown, 1000);
};

You should use $interval. https://docs.angularjs.org/api/ng/service/$interval

Related

Subtract time and show difference in mins:secs format

I want to accurately display the difference between two times. The different should be displayed in a format such as mm:ss
methods: {
calcuateTimeDifference: function (startTime, endTime) {
let result = 0;
if (startTime && endTime) {
let start = startTime.split(":");
let end = endTime.split(':');
let startTimeInHrs = (parseFloat(start[0]/3600) + parseFloat(start[1]/60) + parseFloat(start[2]/3600));
let endTimeInHrs = (parseFloat(end[0]/3600) + parseFloat(end[1]/60) + parseFloat(end[2] /3600));
result = endTimeInHrs - startTimeInHrs;
}
return result.toFixed(2);
},
Using this function - the difference between the following times: 16:03:01 - 16:04:01 - I get the result as -32.00.
split the strings on : to get the hours, minutes, and seconds
convert all to seconds and add them to get the total seconds from each time
subtract the two to get the difference in seconds
convert the difference seconds to hours, minutes and seconds using the modules operator(%)
format the result for appropriate display
let start = "16:03:01";
let end = "16:04:05";
let time = calcuateTimeDifference(start, end);
console.log(time);
function calcuateTimeDifference(startTime, endTime) {
let result = 0;
if (startTime && endTime) {
const start = startTime.split(':').map(Number);
const end = endTime.split(':').map(Number);
const startSeconds = (60*60) * start[0] + 60*start[1] + start[2];
const endSeconds = (60*60) * end[0] + 60*end[1] + end[2];
const diffSeconds = endSeconds - startSeconds;
seconds = parseInt((diffSeconds) % 60);
minutes = parseInt((diffSeconds/60) % 60);
hours = parseInt((diffSeconds/(60*60)) % 24);
//append `0` infront if a single digit
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return `${hours}:${minutes}:${seconds}`;
}
console.log("Invalid Input");
}
function calcuateTimeDifference(startTime, endTime) {
let toSeconds = (time) => {
let [h, m, s] = time.split(':');
return h * 360 + m * 60 + +s;
};
let d = Math.abs(toSeconds(startTime) - toSeconds(endTime));
let mm = String(Math.floor(d / 60));
if (mm.length == 1) mm = '0' + mm;
let ss = String(d % 60);
if (ss.length == 1) ss = '0' + ss;
return `${mm}:${ss}`;
}

JavaScript GetTime Function

My getTime function shows me the current hour, minutes, and seconds without any problem.
My question is how can I call the hours, minutes, and seconds on different spans?
Example
<span id="hours" class="x"></span>
<span id="minutes" class="y"></span>
<span id="seconds" class="z"></span>
JavaScript Function
<script language="JavaScript">
function getTime() {
const timeNow = new Date();
const hours = timeNow.getHours();
const minutes = timeNow.getMinutes();
const seconds = timeNow.getSeconds();
let timeString = '' + ((hours > 24) ? hours - 12 : hours);
timeString += ((minutes < 10) ? ":0" : ":") + minutes;
timeString += ((seconds < 10) ? ":0" : ":") + seconds;
timeString += (hours >= 12) ? "" : "";
//timeString += (hours >= 12) ? " P.M." : " A.M.";
return timeString;
}
const hoursSpan = document.getElementById('Hour');
setInterval(() => {
hoursSpan.textContent = getTime();
}, 1000);
</script>
Try this. Make the variables global to get separate values of hours minutes and seconds. You were using wrong id to get span and the function returns full string so splitted it for only hours
var timeNow = new Date();
var hours = timeNow.getHours();
var minutes = timeNow.getMinutes();
var seconds = timeNow.getSeconds();
function getTime() {
timeNow = new Date();
hours = timeNow.getHours();
minutes = timeNow.getMinutes();
seconds = timeNow.getSeconds();
let timeString = '' + ((hours > 24) ? hours - 12 : hours);
timeString += ((minutes < 10) ? ":0" : ":") + minutes;
timeString += ((seconds < 10) ? ":0" : ":") + seconds;
timeString += (hours >= 12) ? "" : "";
//timeString += (hours >= 12) ? " P.M." : " A.M.";
return timeString;
}
const hoursSpan = document.getElementById('hours');
const min = document.getElementById('minutes');
const sec = document.getElementById('seconds');
setInterval(() => {
hoursSpan.textContent = getTime().split(':')[0];
min.textContent=":"+minutes;
sec.textContent=":"+seconds;
}, 1000);
<span id="hours" class="x"></span>
<span id="minutes" class="y"></span>
<span id="seconds" class="z"></span>
First issue
You have a silly mistake in this line
const hoursSpan = document.getElementById('Hour');
There is no element with the id Hour. Your span element has id hours. You need this instead:
const hoursSpan = document.getElementById('hours');
Second issue
If you plan to use the 3 parts separately, then why join them into a string in the first place? Just make use of the fact that JavaScript functions can return objects!
This looks a lot cleaner!
<span id="hours" class="x"></span>
<span id="minutes" class="y"></span>
<span id="seconds" class="z"></span>
<script>
function getTime() {
const timeNow = new Date();
const hours = timeNow.getHours();
const minutes = timeNow.getMinutes();
const seconds = timeNow.getSeconds();
let hoursString = '' + ((hours > 12) ? hours - 12 : hours);
let minutesString = ((minutes < 10) ? ":0" : ":") + minutes;
let secondsString = ((seconds < 10) ? ":0" : ":") + seconds;
return {
h: hoursString,
m: minutesString,
s: secondsString
};
}
const hoursSpan = document.getElementById('hours');
const minutesSpan = document.getElementById('minutes');
const secondsSpan = document.getElementById('seconds');
setInterval(() => {
const t = getTime();
hoursSpan.textContent = t.h;
minutesSpan.textContent = t.m;
secondsSpan.textContent = t.s;
}, 1000);
</script>
PS: This code could be shortened a lot, but I kept it this way so it's easy to understand.

Adding zeros in a digital clock

I have researched for an hour now on how to do add the zeros whenever hours, minutes or seconds are less 10, to make them, for example, "05 hours", and not just "5 hours".
I have tried if (hours < 10) { hours = "0" + hours } and I've seen it work in a couple of websites, but it doesn't seem to work in my code.
How can I make this work?
function clock() {
//Clock variables
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
var date1 = [hours, minutes, seconds];
var actualDate = date1.join(":");
//Adding zeros, but it doesn't work.
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
//text
document.getElementById("hey").innerHTML = actualDate;
//Repeat every 1000ms (1 second)
setTimeout(clock, 1000);
};
clock();
<h1 id="hey"></h1>
That is because you need to calculate date1 and actualdate after prepending zeroes on the values.
function clock() {
//Clock variables
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
//Adding zeros, but it doesn't work.
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var date1 = [hours, minutes, seconds];
var actualDate = date1.join(":");
//text
document.getElementById("hey").innerHTML = actualDate;
//Repeat every 1000ms (1 second)
setTimeout(clock, 1000);
};
clock();
<h1 id="hey"></h1>
I would suggest you to use padStart of ES8 to do this task.
var x = "5";
console.log(x.padStart(2, "0"));
Better use this pad function :
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
in node :
> function pad(num, size) {
... var s = num+"";
... while (s.length < size) s = "0" + s;
... return s;
... }
> pad(1, 2)
'01'
> pad(11, 2)
'11'
>
if (seconds < 10) { seconds = "0" + seconds; } this will just add the number 0 to the number of seconds. So you have to make your numbers a string:
function clock() {
//Clock variables
var today = new Date();
var hours = today.getHours().toString();
var minutes = today.getMinutes().toString();
var seconds = today.getSeconds().toString();
//Adding zeros, but it doesn't work.
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var date1 = [hours, minutes, seconds];
var actualDate = date1.join(":");
//text
document.getElementById("hey").innerHTML = actualDate;
//Repeat every 1000ms (1 second)
setTimeout(clock, 1000);
};
clock();
<h1 id="hey"></h1>

current time using javascript not grabbing correct location

Running a script to get current time for two specific locations. One time is for Mountain Time and the other is for East Coast Time. I am running into an issue where the Mountain Time clock is displaying time based on Pacific Standard Time if a user is based in a PST location. Rather than having PST is there a way for me to make sure that the two clocks are only getting MT and ET and taking into consideration daylight savings time as well?
$(document).ready(function(){
function timeDisplay() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
//var seconds = currentTime.getSeconds();
var meridiem = " ";
if(hours >= 12){
hours = hours - 12;
meridiem = "pm";
}
else{
meridiem = "am";
}
if(hours === 0){
hours = 12;
}
if(hours < 10){
hours = "0" + hours;
}
if(minutes < 10){
minutes = "0" + minutes;
}
var clockDiv = document.getElementById('stat');
clockDiv.innerText = hours + ":" + minutes + meridiem;
}
timeDisplay();
setInterval(timeDisplay, 1000);
function newYorkTimeDisplay(offset) {
var currentTime = new Date();
currentTime.setHours(currentTime.getHours()+offset);
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
//var seconds = currentTime.getSeconds();
var meridiem = " ";
if(hours >= 12){
hours = hours - 12;
meridiem = "pm";
}
else{
meridiem = "am";
}
if(hours === 0){
hours = 12;
}
if(hours < 10){
hours = "0" + hours;
}
if(minutes < 10){
minutes = "0" + minutes;
}
var newYorkDiv = document.getElementById('newYork');
newYorkDiv.innerText = hours + ":" + minutes + meridiem;
}
newYorkTimeDisplay(+2);
setInterval(newYorkTimeDisplay, 1000, +2);
});
Any help on this is appreciated. Trying to figure out what I am missing.
Thanks in advance.
You need to get the user's current UTC timezone offset and subtract it from New York's Timezone Offset.
var tz_offset = (new Date().getTimezoneOffset()/100) - 3;
newYorkTimeDisplay(tz_offset);
$(document).ready(function() {
function timeDisplay() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
//var seconds = currentTime.getSeconds();
var meridiem = " ";
if (hours >= 12) {
hours = hours - 12;
meridiem = "pm";
} else {
meridiem = "am";
}
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
var clockDiv = document.getElementById('stat');
clockDiv.innerText = hours + ":" + minutes + meridiem;
}
timeDisplay();
setInterval(timeDisplay, 1000);
function newYorkTimeDisplay(offset) {
var currentTime = new Date();
currentTime.setHours(currentTime.getHours() + offset);
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
//var seconds = currentTime.getSeconds();
var meridiem = " ";
if (hours >= 12) {
hours = hours - 12;
meridiem = "pm";
} else {
meridiem = "am";
}
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
var newYorkDiv = document.getElementById('newYork');
newYorkDiv.innerText = hours + ":" + minutes + meridiem;
}
var tz_offset = (new Date().getTimezoneOffset()/100) - 3;
newYorkTimeDisplay(tz_offset);
setInterval(newYorkTimeDisplay, 1000, +2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=newYork></div>
<div id=stat></div>

AngularJS - How do you convert milliseconds to xHours and yMins

I've a requirement where I want to convert milliseconds to xHours and yMins in AngularJS.
For ex. 3600000 should be displayed as 1h 0m.
I tried using date:'H:m' and date:'HH:mm' from the date formats on Angular's website.
But those give 19:0 and 19:00 instead of 1h 0m.
Any pointers of achieving this will be helpful.
Thanks
Let make a custom filter for this, e.g:
.filter('millSecondsToTimeString', function() {
return function(millseconds) {
var oneSecond = 1000;
var oneMinute = oneSecond * 60;
var oneHour = oneMinute * 60;
var oneDay = oneHour * 24;
var seconds = Math.floor((millseconds % oneMinute) / oneSecond);
var minutes = Math.floor((millseconds % oneHour) / oneMinute);
var hours = Math.floor((millseconds % oneDay) / oneHour);
var days = Math.floor(millseconds / oneDay);
var timeString = '';
if (days !== 0) {
timeString += (days !== 1) ? (days + ' days ') : (days + ' day ');
}
if (hours !== 0) {
timeString += (hours !== 1) ? (hours + ' hours ') : (hours + ' hour ');
}
if (minutes !== 0) {
timeString += (minutes !== 1) ? (minutes + ' minutes ') : (minutes + ' minute ');
}
if (seconds !== 0 || millseconds < 1000) {
timeString += (seconds !== 1) ? (seconds + ' seconds ') : (seconds + ' second ');
}
return timeString;
};
});
Then use it:
<div>{{ millSeconds | millSecondsToTimeString }}</div>
There is date converter in AngularJS, just set required date format:
{{milliseconds | date:'yyyy-MM-dd HH:mm'}}
Also I created such 'timeAgo' filter using jQuery timeago() function:
.filter('timeAgo', function() {
return function(input) {
if (input == null) return "";
return jQuery.timeago(input);
};
})
Usage:
{{milliseconds | timeAgo}}
or use together both format for wide date representation:
<span>{{milliseconds | timeAgo}}, {{milliseconds | date:'yyyy-MM-dd HH:mm'}}</span>
Result:
12 minutes ago, 2015-03-04 11:38
You'll want to use moment's duration objects.
To do what you want, try this:
app.controller 'MainCtrl', ($scope) ->
$scope.name = 'World'
$scope.milliseconds = 3600000
$scope.duration = moment.duration($scope.milliseconds)
And the markup
<body ng-controller="MainCtrl">
<p>Milliseconds: {{milliseconds}}</p>
<p>Duration: {{duration.hours()}}h {{duration.minutes()}}m</p>
</body>
plunkr: http://plnkr.co/edit/2HL75Tmr4CoAy5R9smkx
Thanks. I've modified your filter slightly to return duration in hh:mm:ss format.
.filter('duration', function() {
//Returns duration from milliseconds in hh:mm:ss format.
return function(millseconds) {
var seconds = Math.floor(millseconds / 1000);
var h = 3600;
var m = 60;
var hours = Math.floor(seconds/h);
var minutes = Math.floor( (seconds % h)/m );
var scnds = Math.floor( (seconds % m) );
var timeString = '';
if(scnds < 10) scnds = "0"+scnds;
if(hours < 10) hours = "0"+hours;
if(minutes < 10) minutes = "0"+minutes;
timeString = hours +":"+ minutes +":"+scnds;
return timeString;
}
});
For anyone who wants to have comma separators (e.g. '21 days, 14 hours, 7 minutes'):
'use strict';
angular.module('contests').filter('duration', function () {
return function(milliseconds) {
var seconds = Math.floor(milliseconds / 1000);
var days = Math.floor(seconds / 86400);
var hours = Math.floor((seconds % 86400) / 3600);
var minutes = Math.floor(((seconds % 86400) % 3600) / 60);
var dateTimeDurationString = '';
if ((days > 0) && (hours === 0 && minutes === 0)) dateTimeDurationString += (days > 1) ? (days + ' days ') : (days + ' day ');
if ((days > 0) && (hours > 0 || minutes > 0)) dateTimeDurationString += (days > 1) ? (days + ' days, ') : (days + ' day, ');
if ((hours > 0) && (minutes > 0)) dateTimeDurationString += (hours > 1) ? (hours + ' hours, ') : (hours + ' hour, ');
if ((hours > 0) && (minutes === 0)) dateTimeDurationString += (hours > 1) ? (hours + ' hours ') : (hours + ' hour ');
if (minutes > 0) dateTimeDurationString += (minutes > 1) ? (minutes + ' minutes ') : (minutes + ' minute ');
return dateTimeDurationString;
};
});
Try this one
var app = angular.module ( 'myApp', [] ) ;
app.controller ( 'myController', function ( $scope, $filter) {
$scope.date = $filter('date')(milliseconds, 'MM/dd/yyyy');
});
Use below syntax
$filter('date')(dateObj, format)
e.g.
$filter('date')(1324339200000, 'dd/MM/yyyy');
(function () {
'use strict';
angular
.module('module_name')
.filter('secondsToDateTime', secondsToDateTime);
function secondsToDateTime() {
return function(seconds) {
return new Date(1970, 0, 1).setSeconds(seconds);
};
}
})();
<span>{{seconds | secondsToDateTime | date:'HH:mm:ss'}}</span>
For TypeScript but could be adapted for any language.
convertTimeMS(timeMS: number): string {
const seconds = Math.floor(timeMS / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
let str: string = '';
if(hours > 0) {
str = str + hours.toString() + 'h ';
}
if(minutes%60 > 0) {
str = str + Number(minutes%60).toString() + 'm ';
}
if(seconds%60 > 0) {
str = str + Number(seconds%60).toString() + 's ';
}
return str;
}

Categories

Resources