Current code that I have is this, but it is not returning individual values:
I want to make days, hours and minutes individual values to use with another javascript codes..
function convertToDaysHoursMins(time, allowzero = false)
{
if (!allowzero && (time === 0 || time < 1))
return 'unlimited';
else if(allowzero && (time === 0 || time < 1))
return '0m';
let format = '';
days = Math.floor(time / 1440);
if(days > 0) format = format + days + 'd ';
hours = Math.floor(time / 60);
if(hours > 0 && (hours % 24) != 0) format = format + (hours - (days * 24)) + 'h '
format
minutes = (time % 60);
if(minutes > 0) format = format + minutes + 'm';
return [days, hours, minutes];
}
Try this:
function convertToDaysHoursMins(time, allowzero = false)
{
if (!allowzero && (time === 0 || time < 1))
return 'unlimited';
else if(allowzero && (time === 0 || time < 1))
return '0m';
let format = '';
days = Math.floor(time / 1440);
if(days > 0) format = format + days + 'd ';
hours = Math.floor(time / 60);
if(hours > 0 && (hours % 24) != 0) format = format + (hours - (days * 24)) + 'h '
format
minutes = (time % 60);
if(minutes > 0) format = format + minutes + 'm';
if(format !== '')
return format
else
return '-';
}
console.log(convertToDaysHoursMins(4556))
Try this:
function convertToDaysHoursMins(time, allowzero = false)
{
if (!allowzero && (time === 0 || time < 1))
return 'unlimited';
else if(allowzero && (time === 0 || time < 1))
return [0,0,0];
days = Math.floor(time / 1440);
hours = Math.floor(time / 60);
if(hours > 0 && (hours % 24) != 0) hours = hours - (days * 24)
minutes = (time % 60);
return [days, hours, minutes];
}
const result = convertToDaysHoursMins(4556);
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);
Related
Please help me with the code . How i can create alert when time runs out in this code. i want to set alert on when time runs out .
function makeTimer() {
// var endTime = new Date("29 April 2018 9:56:00 GMT+01:00");
var endTime = new Date("29 April 2020 9:56:00 GMT+01:00");
endTime = (Date.parse(endTime) / 1000);
var now = new Date();
now = (Date.parse(now) / 1000);
var timeLeft = endTime - now;
var days = Math.floor(timeLeft / 86400);
var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600)) / 60);
var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
if (hours < "10") {
hours = "0" + hours;
}
if (minutes < "10") {
minutes = "0" + minutes;
}
if (seconds < "10") {
seconds = "0" + seconds;
}
$("#minutes").html(minutes + "<span>Minutes</span>");
$("#seconds").html(seconds + "<span>Seconds</span>");
}
setInterval(function() {
makeTimer();
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="minutes"></span> <span id="seconds"></span>
Just test
const pad = n => ("0" + n).slice(-2);
var endTime = new Date();
// uncomment below
// endTime.setMinutes(endTime.getMinutes() + 15);// 15 minutes
// remove next line, it is just to show how the count down works without waiting 15 minutes
endTime.setSeconds(endTime.getSeconds() + 10);// 10 seconds
endTime = (Date.parse(endTime) / 1000);
function makeTimer() {
var now = new Date();
now = (Date.parse(now) / 1000);
var timeLeft = endTime - now;
var days = Math.floor(timeLeft / 86400);
var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600)) / 60);
var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
$("#minutes").html(pad(minutes) + " <span>Minute" + (minutes === 1 ? "" : "s") + "</span>");
$("#seconds").html(pad(seconds) + " <span>Second" + (seconds === 1 ? "" : "s") + "</span>");
if (seconds === 0 && minutes === 0) {
console.log("Done")
clearInterval(tId);
}
}
const tId = setInterval(makeTimer, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="minutes"></span> <span id="seconds"></span>
Inside the function,you can simply check the values of hours, minutes and seconds.As you already have it, you can simply put an if condition to check whether the hour is 0 and minute is 0 and second is 0. Then in that condition you can simply send an alert message.
I've got some code for a daily countdown timer which counts down to 12 noon every day. I want to exclude weekends which I've done like this:
if((t.total<=0) || (day === 0) || (day === 6)){
clearInterval(timeinterval);
document.getElementById('deadline_Container').style.display = "none";
}
}
However, I also need to do this for a certain date, so that the countdown won't show between 20.12. to 27.12. for example. Not sure how to do this for a specific date?
This is my whole code:
<script type="text/javascript">
var today = new Date(new Date().getTime());
var deadline = new Date(Date.UTC(today.getFullYear(),today.getMonth(), today.getDate(), 11, 59, 59));
function time_remaining(endtime){
var t = endtime - new Date();
var seconds = Math.floor( (t/1000) % 60 );
var minutes = Math.floor( (t/1000/60) % 60 );
var hours = Math.floor( (t/(1000*60*60)) % 24 );
return {'total':t, 'hours':hours, 'minutes':minutes, 'seconds':seconds};
}
function run_clock(id,endtime){
var clock = document.getElementById(id);
if (null === clock) {
return;
}
var hours_span = clock.querySelector('.hours');
var minutes_span = clock.querySelector('.minutes');
var seconds_span = clock.querySelector('.seconds');
function update_clock(){
var t = time_remaining(endtime);
hours_span.innerHTML = ('0' + t.hours).slice(-2);
minutes_span.innerHTML = ('0' + t.minutes).slice(-2);
seconds_span.innerHTML = ('0' + t.seconds).slice(-2);
day = today.getDay();
if((t.total<=0) || (day === 0) || (day === 6)){
clearInterval(timeinterval);
document.getElementById('deadline_Container').style.display = "none";
}
}
update_clock();
var timeinterval = setInterval(update_clock,1000);
}
run_clock('clockdiv',deadline);
</script>
<div id="deadline_Container">
<div id="clockdiv">
<!-- <div><span class="days"></span><span class="smalltext">Days</span></div> -->
<div><span class="hours"></span><span class="smalltext">Hours</span></div>
<div><span class="minutes"></span><span class="smalltext">Minutes</span></div>
<div class="clockLast"><span class="seconds"></span><span class="smalltext">Seconds</span></div>
</div>
</div>
You could add an extended condition to check the day and the month:
const dayOfMonth = today.getDate();
const month = today.getMonth() + 1;
if ((t.total <= 0) || (day === 0) || (day === 6) || (dayOfMonth >= 20 && dayOfMonth <= 27 && month == 12)) {
...
The full code would be:
var today = new Date(new Date().getTime());
var deadline = new Date(Date.UTC(today.getFullYear(), today.getMonth(), today.getDate(), 11, 59, 59));
function time_remaining(endtime) {
var t = endtime - new Date();
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
return {
'total': t,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function run_clock(id, endtime) {
var clock = document.getElementById(id);
if (null === clock) {
return;
}
var hours_span = clock.querySelector('.hours');
var minutes_span = clock.querySelector('.minutes');
var seconds_span = clock.querySelector('.seconds');
function update_clock() {
var t = time_remaining(endtime);
hours_span.innerHTML = ('0' + t.hours).slice(-2);
minutes_span.innerHTML = ('0' + t.minutes).slice(-2);
seconds_span.innerHTML = ('0' + t.seconds).slice(-2);
day = today.getDay();
const dayOfMonth = today.getDate();
const month = today.getMonth() + 1;
if ((t.total <= 0) || (day === 0) || (day === 6) || (dayOfMonth >= 20 && dayOfMonth <= 27 && month === 12)) {
clearInterval(timeinterval);
document.getElementById('deadline_Container').style.display = "none";
}
}
update_clock();
var timeinterval = setInterval(update_clock, 1000);
}
run_clock('clockdiv', deadline);
<div id="clockdiv">
<span class="hours"></span>
<span class="minutes"></span>
<span class="seconds"></span>
</div>
To check if one date is between two other, use bigger than and smaller than:
if(firstDate < actualDate && lastDate > actualDate){
//your code
}
To check only one, you can use .getTime() or .valueOf() and compare them:
comparableDate.getTime() == actualDate.getTime()
comparableDate.valueOf() == actualDate.valueOf()
If you only need to compare the date(not the time) I think .setHours(hour, min, sec, milisec) would be helpful:
var dateWithoutTime = actualDate;
dateWithoutTime.setHours(0,0,0,0);
I am trying to calculate the hours between two times.
Below is where I am currently but this code fails in two ways.
1). I need .Hours to output time in decimal.
(e.g one and half hours should output 1.5 and 15mins should be 0.25).
2). Calculation currently does not treat values for time as time.
(e.g 23:00 to 2:00 should equal 3 and NOT -21 as currently).
HTML
<input class="Time1" value="10:00" />
<input class="Time2" value="12:00" />
<input class="Hours" value="0" />
JQUERY
$(function () {
function calculate() {
var hours = parseInt($(".Time2").val().split(':')[0], 10) - parseInt($(".Time1").val().split(':')[0], 10);
$(".Hours").val(hours);
}
$(".Time1,.Time2").change(calculate);
calculate();
});
http://jsfiddle.net/44NCk/
Easy way is if you get a negative value, add 24 hours to it and you should have your result.
var hours = parseInt($(".Time2").val().split(':')[0], 10) - parseInt($(".Time1").val().split(':')[0], 10);
// if negative result, add 24 hours
if(hours < 0) hours = 24 + hours;
Demo: http://jsfiddle.net/44NCk/1/
Getting the minutes as a decimal involves a bit more as you can see in thsi fiddle: http://jsfiddle.net/44NCk/2/
function calculate() {
var time1 = $(".Time1").val().split(':'), time2 = $(".Time2").val().split(':');
var hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
var hours = hours2 - hours1, mins = 0;
// get hours
if(hours < 0) hours = 24 + hours;
// get minutes
if(mins2 >= mins1) {
mins = mins2 - mins1;
}
else {
mins = (mins2 + 60) - mins1;
hours--;
}
// convert to fraction of 60
mins = mins / 60;
hours += mins;
hours = hours.toFixed(2);
$(".Hours").val(hours);
}
function timeobject(t){
a = t.replace('AM','').replace('PM','').split(':');
h = parseInt(a[0]);
m = parseInt(a[1]);
ampm = (t.indexOf('AM') !== -1 ) ? 'AM' : 'PM';
return {hour:h,minute:m,ampm:ampm};
}
function timediff(s,e){
s = timeobject(s);
e = timeobject(e);
e.hour = (e.ampm === 'PM' && s.ampm !== 'PM' && e.hour < 12) ? e.hour + 12 : e.hour;
hourDiff = Math.abs(e.hour-s.hour);
minuteDiff = e.minute - s.minute;
if(minuteDiff < 0){
minuteDiff = Math.abs(60 + minuteDiff);
hourDiff = hourDiff - 1;
}
return hourDiff+':'+ Math.abs(minuteDiff);
}
difference = timediff('09:10 AM','12:25 PM'); // output 3:15
difference = timediff('09:05AM','10:20PM'); // output 13:15
$(function () {
function calculate() {
var time1 = $(".Time1").val().split(':'), time2 = $(".Time2").val().split(':');
var hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10),
seconds1 = parseInt(time1[2], 10),
seconds2 = parseInt(time2[2], 10);
var hours = hours2 - hours1, mins = 0, seconds = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
}
else {
mins = (mins2 + 60) - mins1;
hours--;
}
if (seconds2 >= seconds1) {
seconds = seconds2 - seconds1;
}
else {
seconds = (seconds2 + 60) - seconds1;
mins--;
}
seconds = seconds/60;
mins += seconds;
mins = mins / 60; // take percentage in 60
hours += mins;
//hours = hours.toFixed(4);
$(".Hours").val(hours);
}
$(".Time1,.Time2").change(calculate);
calculate();
});
Here is an HTML Code
<input type="text" name="start_time" id="start_time" value="12:00">
<input type="text" name="end_time" id="end_time" value="10:00">
<input type="text" name="time_duration" id="time_duration">
Here is javascript code
function timeCalculating()
{
var time1 = $("#start_time").val();
var time2 = $("#end_time").val();
var time1 = time1.split(':');
var time2 = time2.split(':');
var hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
var hours = hours2 - hours1, mins = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
}
else {
mins = (mins2 + 60) - mins1;
hours--;
}
if(mins < 9)
{
mins = '0'+mins;
}
if(hours < 9)
{
hours = '0'+hours;
}
$("#time_duration").val(hours+':'+mins);
}
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;
}
i have an if statement to change time back to 12 after it hits 11:45:
i = (i >= 192) ? i - 192 : ( i >= 96) ? i - 96 : i
var mins = (i * 15 % 60)
var hours = Math.floor(i * 15 / 60)
var ampm = (hours >= 12) ? "PM" : "AM"
hours = (hours == 0) ? 12 : (hours >= 12) ? hours - 12 : hours;
var nextMins, nextHours = hours;
switch (mins) {
case 0:
mins = "";
nextMins = 15;
break;
case 45:
nextMins = "";
nextHours = hours+1;
break;
default:
nextMins = mins + 15;
break;
}
var time = hours + (mins == "" ? "" : ":" + mins) + " - " + nextHours + (nextMins == "" ? "" : ":" + nextMins) + ampm
it changes in 15 minute intervals, the issue is it will start at 12 but after it gets to 12:00 again it will display as 0:15, 0:30, 0:45. Instead of 12:15, 12:30, 12:45
I thought this part of the if statement would do it:
hours = (hours == 0) ? 12
but isn't working?
The simplest way is probably
hours = (hours % 12) || 12;
This way copes with any positive integer for hours (eg. 36 will still return 12).
It should read
hours = (hours == 0) ? 12 : (hours > 12) ? hours - 12 : hours;
By having >= you're currently including 12 as a number to deduct 12 from.
hours = (hours == 0) ? 12 : hours;
is the complete usage of ternary conditional. But why don't you use a simple if statement?
if(hours == 0)
hours = 12;