I've been working on this script to get the difference between 2 dates. But the hours will mess up the script (http://jsfiddle.net/HuGvd/).
When the script enters a new month new the same day the script stops working correctly. I've also tried adding minutes to this script with no luck really need help with this one guys.
function getDateDiff(timestamp) {
if (null === timestamp || timestamp === "" || timestamp === "undefined") return "?";
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var d1 = new Date();
var d1Y = d1.getFullYear();
var d2Y = parseInt(splitDate[0], 10);
var d1M = d1.getMonth() + 1;
var d2M = parseInt(splitDate[1], 10);
var d1D = d1.getDate();
var d2D = parseInt(splitDate[2], 10);
var d1H = d1.getHours();
var d2H = parseInt(splitTime[0], 10);
var diffInHours = (d1H + 24 * d1D + 30) - (d2H + 24 * d2D + 30);
if (diffInHours < 24) return diffInHours + " hour";
var diffInDays = (d1D + 30 * d1M + 12) - (d2D + 30 * d2M + 12);
if (diffInDays < 7) return diffInDays + " days";
else if (diffInDays >= 7 && diffInDays < 14) return "1 week";
else if (diffInDays >= 14 && diffInDays < 30) return Math.floor(diffInDays / 7) + " weeks";
var diffInMonths = (d1M + 12 * d1Y) - (d2M + 12 * d2Y);
if (diffInMonths <= 1) return "1 month";
else if (diffInMonths < 12) return diffInMonths + " months";
var diffInYears = Math.floor(diffInMonths / 12);
if (diffInYears <= 1) return "1 year";
else if (diffInYears < 12) return diffInYears + " years";
}
Date/time functionality is extremely complex with more edge cases than you can possibly cover... don't roll your own solution, use built-in functionality. You can find the number of milliseconds between two dates in javascript like this:
var now = new Date();
var then = new Date(timestamp);
var diffMS = now - then;
From there, it's not too difficult to convert to whatever unit your want based on how you want to display it.
http://jsfiddle.net/AMDXq/
As a side note, this is a fairly common problem. I haven't looked, but I'm sure there's a plugin or library out there for this.
Here is a solution for finding the difference between two dates. The strategy is to convert strings to date objects, then calculate the difference and return an array of values for years, months, days, etc.
I've added a parameter for "precise" so that by default it returns a value in whole days (e.g. 2013-08-13T23:59:59Z to 2013-08-14T00:00:01Z is one day) or precise (where the above difference is 2 seconds).
// Expects start date to be before end date
// Default is to deal in whole days. For precise differences
// (hours, minutes and seconds), set precise to true
function dateDifference(start, end, precise) {
var timeDiff, years, months, days, hours, minutes, seconds;
// Copy date objects so don't modify originals
var s = new Date(+start);
var e = new Date(+end);
console.log(s, e);
// If not precise, set h,m,s to zero
if (!precise) {
s.setUTCHours(0,0,0,0);
e.setUTCHours(0,0,0,0);
console.log(s, e);
}
// Get estimate of year difference
years = e.getUTCFullYear() - s.getUTCFullYear();
// Add difference to start, if greater than end, remove one year
// Note start from restored start date as adding and subtracting years
// may not be symetric
s.setFullYear(s.getUTCFullYear() + years);
if (s > e) {
--years;
s = new Date(+start);
s.setFullYear(s.getUTCFullYear() + years);
}
// Get estimate of months
months = e.getUTCMonth() - s.getUTCMonth();
months += months < 0? 12 : 0;
// Add difference to start, adjust if greater
s.setUTCMonth(s.getUTCMonth() + months);
if (s > e) {
--months;
s = new Date(+start);
s.setUTCFullYear(s.getUTCFullYear() + years);
s.setUTCMonth(s.getUTCMonth() + months);
}
// Get remaining time difference
timeDiff = e - s;
days = timeDiff / 8.64e7 | 0;
hours = (timeDiff % 8.64e7) / 3.6e6 | 0;
minutes = (timeDiff % 3.6e6) / 6e4 | 0;
seconds = ((timeDiff % 6e4) / 1e3).toFixed(3);
console.log(years, months, days, hours, minutes, seconds);
return [years, months, days, hours, minutes, seconds];
}
// Simple caluculation of days between two ES5 date objects
function daysDifference(start,end) {
return ((end - start) / 8.64e7).toFixed(2);
}
// Expects input in ISO8601 format: yyyy-mm-ddThh:mm:ss.sssZ
function dateFromString(s) {
s = s.split(/\D/);
s[6] = s[6]? ('0.'+ s[6]) * 1000 : 0;
return new Date(Date.UTC(s[0],--s[1],s[2],s[3],s[4],s[5],s[6]));
}
function getDateDiff(start, end, precise) {
var d = dateDifference(dateFromString(start), dateFromString(end), precise);
return d[0] + ' years, ' + d[1] + ' months, ' + d[2] + ' days' +
(precise? ', ' + d[3] + ' hours, ' + d[4] + ' minutes and ' + d[5] + ' seconds' : '') ;
}
function getDaysDiff(start, end) {
var d = daysDifference(dateFromString(start), dateFromString(end));
return d + ' days';
}
</script>
<!-- Some HTML to show how to use it -->
<form onsubmit="this.doCalc.onclick(); return false;">
<label for="startDate">Start date (yyyy-mm-dd)<input name="startDate" id="startDate"
value="2012-08-09T22:15:03.22" size="25"></label>
<br>
<label for="endDate">End date (yyyy-mm-dd)<input name="endDate" id="endDate"
value="2013-08-13T12:10:03.22" size="25"></label>
<br>
<label for="dateDifference">Date difference: <input name="dateDifference" readonly size="100"></label>
<br>
<label for="daysDifference">Days difference: <input name="daysDifference" readonly size="100"></label>
<br>
<label for="precise"><input type="checkbox" value="precise" name="precise" id="precise">Precise?</label>
<br>
<input type="button" value="Calculate…" name="doCalc" onclick="
this.form.dateDifference.value = getDateDiff(this.form.startDate.value, this.form.endDate.value,
this.form.precise.checked);
this.form.daysDifference.value = getDaysDiff(this.form.startDate.value, this.form.endDate.value);
">
<input type="reset">
</form>
Related
I've created a booking calculator by date using JavaScript.
Basically I want the base price to be £25 for 1 day (24 hours) or less, and £10 for each additional day (each additional 24 hours).
Below is the main part of the code.
jQuery(document).ready(function($) {
var prequote=25.00;
var taxa = 10.00;
var hoje = new Date();
hoje=hoje.getTime();
i = 0;
$('#quote').click(function(event) {
var d1= $('#d1').val();
var d2= $('#d2').val();
var t1= $('#t1').val();
var t2= $('#t2').val();
console.log(d1);
console.log(d2);
console.log(t1);
console.log(t2);
// end - start returns difference in milliseconds
var date2 = new Date(d2);
var date1 = new Date(d1);
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = date2.getTime() - date1.getTime();
// get days
var d = millisBetween / millisecondsPerDay;
//alert ('value of days is:' +d);
//alert ( new Date("1970-1-1 " + t2) - new Date("1970-1-1 " + t1) ) / 1000 / 60 / 60;
var h= ( new Date("1970-1-1 " + t2) - new Date("1970-1-1 " + t1) ) / 1000 / 60 / 60;
//alert ('value of hours is:' +h);
t1 =t1.split(':');
t2 =t2.split(':');
var dat1 = d1.split("-");
var dd1 = dat1[2];
var mm1 = dat1[1];
var yy1 = dat1[0];
var hh1 = t1[0];
var ms1 = t1[1];
var dat2 = d2.split("-");
var dd2 = dat2[2];
var mm2 = dat2[1];
var yy2 = dat2[0];
var hh2 =t2[0];
var ms2 = t2[1];
var x1 = yy1 + ',' + mm1 + ',' + dd1 + ' ' + hh1 + ':' + ms1;
var x2 = yy2 + ',' + mm2 + ',' + dd2 + ' ' + hh2 + ':' + ms2;
var ent = dd1 + '/'+ mm1 +'/'+yy1+' '+ hh1 + ':' + ms1;
var ext = dd2 + '/'+ mm2 +'/'+yy2+' '+ hh2 + ':' + ms2;
var xi = yy1 + ',' + mm1 + ',' + dd1 ;
var xj = yy2 + ',' + mm2 + ',' + dd2 ;
var start =new Date(x1);
//var start_i =new Date(xi);
var end = new Date(x2);
// var end_i = new Date(xj);
start = start.getTime();
end= end.getTime();
if(start === end){
alert('Min rental days is 1');
}
else if(start < end){
// hh1 = parseInt(hh1);ms1 = parseInt(ms1);hh2 = parseInt(hh2);ms2 = parseInt(ms2);;
/*while(start_i < end_i){
i++;
var newDate = start_i.setDate(start_i.getDate() + 1);
start_i = new Date(newDate);
}*/
i=d;
if(i >= 1 ){
if(h > 0 ){
i=i+1;
}
prequote = prequote + (taxa * (i-2));
prequote = parseFloat(prequote.toFixed(2));
}
$('#en-tex').text(ent);
$('#ex-t').text(ext);
$('#prequote').html(prequote);
$('#modal-img').modal('show');
prequote=25.00;
$('#tupd').val(ent);
$('#tdod').val(ext);
}
else{
alert('Please fill in all the date and time fields.');
}
});
The 1st issue is, if I select for example Monday 21st at 9:00am to Tuesday 22nd at 9:00am it doesn't count the fee as for 24 hours. Only if the end date is AFTER 9:00am.
Likewise for longer dates, it only charges for a day AFTER 24 hours and not from 24 hours on the dot.
2nd issue is, if somebody selects less than 24 hours (i.e Monday 21st at 9:00am to Tuesday 22nd at 7:00am) it minuses the £10 from £25. I want it to still quote the base price of £25.
I advise you to use momentJS. Is pretty easy to use.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
Or just like that:
var a = moment('2016-06-06T21:03:55');//now
var b = moment('2016-05-06T20:03:55');
console.log(a.diff(b, 'minutes')) // 44700
console.log(a.diff(b, 'hours')) // 745
console.log(a.diff(b, 'days')) // 31
console.log(a.diff(b, 'weeks')) // 4
Edit.:
Adding some ideas. You can just simply use the example of #jeff:
dt1 = new Date('2016-01-21 20:00:00');
dt2 = new Date('2016-01-24 09:00:00');
dif = dt2-dt1;
dif = dif / ( 1000 * 60 * 60 * 24 );
days = Math.ceil(dif);
var total = 0;
if (days > 0) {
total = 25 + ( (days-1) * 10 ) // total = <first day with prequote 25 and then others days are 10 bucks>
}
console.log(total); // total of amout to be paid
Maybe thia can solve your issue.
Since you are working with whole days you can simplify the process by:
dt1 = new Date('2016-01-21 09:00:00');
dt2 = new Date('2016-01-22 09:00:00');
dif = dt2-dt1;
dif = dif / ( 1000 * 60 * 60 * 24 );
days = Math.ceil(dif);
The days value contains a whole number for the amount of days between the two dates. Do your pricing from this value.
When some one rent room for less than 24 hour. Value of i is become negative. From your expression
prequote = prequote + (taxa * (i-2));
If i is smaller than 2. taxa variable become negative and you have get price less than 25. Please use this below line
i=(i<2)?i=2:i;
From above expression. Your value cannot be smaller than £25. Hope it helps you
How do I get the time difference of two values of 24hr format?
For example
var time1 = 22:30:00,
time2 = 06:30:00;
Difference should come as 08:00:00
You are much better off to do this type of maths with full date objects, otherwise you have to make guesses about the time values such as if the finish is less that the start, it must be on the next day.
The following includes a couple of helper functions and a main function to get the difference.
// Convert h:m:s to seconds
function hmsToSecs(s) {
var b = s.split(':');
return b[0]*3.6e3 + b[1]*60 + +b[2];
}
// Convert seconds to hh:mm:ss
function secsToHMS(n) {
function z(n){return (n<10? '0':'') + n;}
var sign = n < 0? '-' : '';
n = Math.abs(n);
return sign + z(n/3.6e3|0) + ':' + z(n%3.6e3/60|0) + ':' + z(n%60);
}
// Calculate time difference between two times
// start and finish in hh:mm:ss
// If finish is less than start, assume it's the following day
function timeDiff(start, finish) {
var s = hmsToSecs(start);
var f = hmsToSecs(finish);
// If finish is less than start, assume is next day
// so add 24hr worth of seconds
if (f < s) f += 8.64e4;
return secsToHMS(f - s);
}
console.log(timeDiff('22:30:00','06:30:00')); // 08:00:00
console.log(timeDiff('06:30:00','22:30:00')); // 16:00:00
Using full date objects, you can do:
var start = new Date(2014,5,5,22,30); // 22:30:00 on 5 June 2014
var finish = new Date(2014,5,6,6,30); // 06:30:00 on 6 June 2014
// Subtract dates to get difference in ms, convert to seconds and format
console.log(secsToHMS((finish - start)/1000)); // 08:00:00
console.log(secsToHMS((start - finish)/1000)); // -08:00:00
I Suggest that you should use jquery date.js library and then you can use its Timespan class like below:
var future = Date.parseExact("22:30:00", "hh:mm:ss");
var past = Date.parseExact("06:30:00", "hh:mm:ss");
var span = new TimeSpan(future - now);
and your difference in hours is as below:
span.getHours() + ":" span.getMinutes() + ":" span.getSeconds()
If you want Diff function in C#;
DateTime oldDate= "06/01/2014 12:00:00 AM";
TimeSpan timeDiff = DateTime.Now - oldDate;
int diff =Convert.ToInt32(timeDiff.TotalHours);
if you want it in JavaScript thats a script block should help you;
function diffDateTime(startDT, endDT) {
if (typeof startDT == 'string' && startDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}[amp ]{0,3}$/i)) {
startDT = startDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}/);
startDT = startDT.toString().split(':');
var obstartDT = new Date();
obstartDT.setHours(startDT[0]);
obstartDT.setMinutes(startDT[1]);
obstartDT.setSeconds(startDT[2]);
}
else if (typeof startDT == 'string' && startDT.match(/^now$/i)) var obstartDT = new Date();
else if (typeof startDT == 'string' && startDT.match(/^tomorrow$/i)) {
var obstartDT = new Date();
obstartDT.setHours(24);
obstartDT.setMinutes(0);
obstartDT.setSeconds(1);
}
else var obstartDT = new Date(startDT);
if (typeof endDT == 'string' && endDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}[amp ]{0,3}$/i)) {
endDT = endDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}/);
endDT = endDT.toString().split(':');
var obendDT = new Date();
obendDT.setHours(endDT[0]);
obendDT.setMinutes(endDT[1]);
obendDT.setSeconds(endDT[2]);
}
else if (typeof endDT == 'string' && endDT.match(/^now$/i)) var obendDT = new Date();
else if (typeof endDT == 'string' && endDT.match(/^tomorrow$/i)) {
var obendDT = new Date();
obendDT.setHours(24);
obendDT.setMinutes(0);
obendDT.setSeconds(1);
}
else var obendDT = new Date(endDT);
var secondsDiff = (obendDT.getTime() - obstartDT.getTime()) > 0 ? (obendDT.getTime() - obstartDT.getTime()) / 1000 : (86400000 + obendDT.getTime() - obstartDT.getTime()) / 1000;
secondsDiff = Math.abs(Math.floor(secondsDiff));
var oDiff = {}; // object that will store data returned by this function
oDiff.days = Math.floor(secondsDiff / 86400);
oDiff.totalhours = Math.floor(secondsDiff / 3600); // total number of hours in difference
oDiff.totalmin = Math.floor(secondsDiff / 60); // total number of minutes in difference
oDiff.totalsec = secondsDiff; // total number of seconds in difference
secondsDiff -= oDiff.days * 86400;
oDiff.hours = Math.floor(secondsDiff / 3600); // number of hours after days
secondsDiff -= oDiff.hours * 3600;
oDiff.minutes = Math.floor(secondsDiff / 60); // number of minutes after hours
secondsDiff -= oDiff.minutes * 60;
oDiff.seconds = Math.floor(secondsDiff); // number of seconds after minutes
return oDiff;
}
usage;
var objDiff = diffDateTime('06/01/2014 12:00:00 AM', 'now');
var dtdiff = objDiff.days + ' days, ' + objDiff.hours + ' hours, ' + objDiff.minutes + ' minutes, ' + objDiff.seconds + ' seconds';
Important: You have to remember that DateTime format must be in en-US format dd/MM/yyyy hh:mm:ss.
I'd like to calculate the elapsed time between two dates. I saw some examples on the internet (most of them on this site), but found nothing useful. I'd like to write a function can call like this:
calculateDifference('2012-02-01 15:31')
There is no second parameter, since it is the current date. I have a code I'm currently using, which is:
function get_time_diff(_datetime )
{
var datetime = new Date( _datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return " on " + _datetime;
}
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var date_diff = new Date( milisec_diff );
var respvalue ='';
if (days > 0) {
respvalue += days + " day(s), ";
}
if (date_diff.getHours() > 0) {
respvalue += (date_diff.getHours() - 1) + " hour(s) and ";
}
respvalue += date_diff.getMinutes() + " minute(s) ago.";
return respvalue;
}
And the result is and should be:
1 day(s), 14 hour(s) and 17 minute(s)
For some reasons there are differences (when 1 day passed it shows 0 etc) and it works only with chrome, in IE and FF it returns with the date I passed as the parameter.
Once again: I'd like to calculate the difference between the current date and a given date in the next format:
1 day(s), 14 hour(s) and 17 minute(s)
I don't care about the months, years. Only hours, mins and secs. Thank you in advance!
Try this:
function get_time_diff(_datetime )
{
var datetime = new Date( _datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return " on " + _datetime;
}
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var hours = Math.floor(milisec_diff / (1000 * 60 * 60) - days * 24);
var minutes = Math.floor(milisec_diff / (1000 * 60) - days * 24 * 60 - hours * (60));
var respvalue ='';
if (days > 0) {
respvalue += days + " day(s), ";
}
if (hours > 0) {
respvalue += hours + " hour(s) and ";
}
respvalue += minutes + " minute(s) ago.";
return respvalue;
}
The problem is that your date format is not valid, so Firefox can't parse your strings as dates.
You can use
function get_time_diff(datetime) {
var milisec_diff = Math.abs(new Date() - new Date(datetime)),
diff = new Date(milisec_diff),
days = milisec_diff / 3600e3 / 24 | 0,
hours = diff.getUTCHours(),
respvalue = '';
if (days)
respvalue += days + " day(s), ";
if (hours)
respvalue += hours + " hour(s) and ";
respvalue += diff.getUTCMinutes() + " minute(s) ago.";
return respvalue;
}
get_time_diff('2012-02-01T15:31Z');
Where the date 2012-02-01T15:31Z is in ISO8601, and the Z means UTC time (note some browsers may not support it).
This seems simplest to me:
http://jsbin.com/tusul/9/edit
// end date is optional, it will assume the current date if not supplied.
// if timezone is not supplied, it will assume local browser time.
function calculateDateDiff(beginDate, endDate) {
var currentDate;
if (typeof(endDate) == 'undefined') {
currentDate = new Date();
} else {
currentDate = new Date(endDate);
}
var targetDate = new Date(beginDate);
var differenceDate;
if (currentDate > targetDate) {
differenceDate = new Date(currentDate - targetDate);
} else {
differenceDate = new Date(targetDate - currentDate);
}
return('Days: ' + (differenceDate.getUTCDate() -1) + ', Hours: ' + differenceDate.getUTCHours() + ', Minutes: ' + differenceDate.getUTCMinutes() + ', Seconds: ' + differenceDate.getUTCSeconds());
}
console.log(calculateDateDiff('05-22-2014 01:02:03', '05-22-2014 02:03:04'));
console.log(calculateDateDiff('05-22-2014 01:02:03', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03Z', '05-22-2014 02:03:04Z'));
console.log(calculateDateDiff('05-22-2014 01:02:03Z', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03-500', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03+1000', '05-22-2014 02:03:04-600'));
The following code is used to get a date value and then add two hours to it. I would really like to know how to give a condition to add that two hours only between 08:30 in the morning until 18:30 of the evening and skip both the days ( Saturday,Sunday ).
For example: if the given date was in 17:30 of Tuesday so it followed the rule it will be ( 17:30 (of Tuesday ) + 2 = 09:30 ( of Wednesday-the next day) and if the given date was in 17:00 (of Friday) it will be if we skip the week-ends 09:00 ( of Monday-skip week-ends ) etc...
var now = new Date(Date.parse($(".x-form-hidden.x-form-field :eq(0)").val()));
now.setHours(now.getHours() + 2);
var dayVar = "";
if (now.getDate() < 10) {
dayVar = 0 + "" + now.getDate()
} else {
dayVar = now.getDate();
}
var dateString =
now.getFullYear() + "-" +
(now.getMonth() + 1) + "-" +
dayVar + " " +
now.getHours() + ":" + now.getMinutes() + ":0" + now.getSeconds();
$(".x-form-hidden.x-form-field :eq(1)").attr('value', dateString);
function addTwoHours(date) {
//date to decimal
var day = date.getDay() - 1;
var hour = date.getHours() - 8;
var decimal = day * 10 + hour;
//add two hours
decimal += 2;
//decimal to date
var newDay = Math.floor(decimal / 10);
var nextDay = newDay - day == 1;
var weekEnd = newDay % 5 == 0;
var newHour = (decimal % 10) + 8;
var newDate = new Date(date.getTime() + (nextDay?24:0) * (weekEnd?3:1) * 60 * 60 * 1000);
newDate.setHours(newHour);
return newDate;
}
Your time range represent 10 hours per day for 5 days a week, so it's easy to map to a continuous block of 50 hours. Considering then the units and tens gives the shift.
The following example gets the date for Friday 1 Feb. 17:15, which returns Monday 4 Feb 9:15. addTwoHours(new Date(2013, 1, 1, 17, 15));
I have the time stored as a fraction (done so it can be displayed on a graph), e.g. 15.5 is 3.30pm and 23.25 is 11.15pm. I need to turn those numbers into strings in the format HH:MM:SS. Is there a simple way of doing this?
var fraction = 23.5;
var date = new Date(2000, 1, 1); // use any date as base reference
date.setUTCSeconds(fraction * 3600); // add number of seconds in fractional hours
Then use a date formatting script such as this, or Date.js if you're not fond or formatting and padding.
date.format("HH:MM:ss"); // 23:30:00
See an example. I'm using the formatting function from here.
Something like this ?
var fraction = 14.5;
var hours = Math.floor(fraction); // extract the hours (in 24 hour format)
var mins = 60 * (fraction - hours); // calculate the minutes
t = new Date(); // create a date/time object
t.setHours(hours); // set the hours
t.setMinutes(mins); // set the mins
console.log(t.toTimeString()); //show it
or completely manual
var fraction = 14.5;
var hours = Math.floor(fraction);
var mins = 60 * (fraction - hours);
var ampm = ((fraction % 24) < 12) ? 'am' : 'pm';
formatted = ('0' + hours % 12).substr(-2) + ':' + ('0' + mins).substr(-2) + ':00 ' + ampm;
console.log(formatted);
Update
And a version with seconds as well..
var fraction = 14.33;
var hours = Math.floor(fraction);
var allseconds = 3600 * (fraction - hours);
var minutes = Math.floor(allseconds / 60);
var seconds = Math.floor(allseconds % 60);
var ampm = ((fraction % 24) < 12) ? 'am' : 'pm';
formatted = ('0' + hours % 12).substr(-2) + ':' + ('0' + minutes).substr(-2) + ':' + ('0' + seconds).substr(-2) + ' ' + ampm;
console.log(formatted);
Manual function:
var time = function(num) {
if(num < 0 || num >= 24) {throw "Invalid number");}
var x = num > 13 ? num - 12 : num;
var h = Math.floor(x);
var min = x - h;
var ampm = num >= 12 && num < 24 ? "pm" : "am";
return (h + ":" + Math.floor(min * 60) + ampm);
};
Tests:
time(13.40); // 1:24pm
time(11.25); // 11:15pm
time(12.50); // 12:30pm
time(23.50); // 11:30pm
time(0.50); // 0:30am
time(24.00); // error!!