Convert decimal representing time to hour, minutes, seconds - math

I have a decimal. The range of this decimal is between 0 and 23.999999. This decimal represents a time. For example, if the decimal is 0.25, then the time it represents is 12:15 AM. If the decimal is 23.50, the time it represents is 11:30 PM.
I have three variables:
- Hours
- Minutes
- Seconds
Using this decimal, how do I fill in the Hours, Minutes, and Seconds values?

Well, here's an answer in C#, but it's generally the same idea in most languages:
int hours = (int)hoursDecimal;
decimal minutesDecimal = ((hoursDecimal - hours) * 60);
int minutes = (int)minutesDecimal;
int seconds = (int)((minutesDecimal - minutes) * 60);

The hours should be pretty easy.
There are 60 minutes in 1 hour, so get the decimal part, multiply it by 60, and take the integer. Take the decimal again, multiply it again by 60, and you have your seconds.
For example, let's take the number 20.38490
We know it's hour 20, or 8 PM.
This leaves us with the number .38490
Multiplying with 60, we get 23.094 minutes.
Multiplying .094 with 60, we get 5 seconds.

you can use the floor function to strip off the hours and leave the minuites and seconds as a fraction of an hour. Then you can use the floor function again to strip off the minuites as a fraction of an hour. you are then left with the seconds ( as fractions of an hour )
below a simple example to print hours and mins sunrise is in fractional hours since midnight
printf( "sunrise %ld:%ld, \n",
(long)floor( sunrise ),
(long)(floor( sunrise * 60 ) - 60 * floor( sunrise )) );

Whatever language you use, you can do this using the math functions: MOD and FLOOR/TRUNC
Let "dec" be the decimal variable
trunc(mod(dec, 1)) => hours
trunc(mod(dec * 60, 60)) => minutes
trunc(mod(dec * 3600, 60)) => seconds
In C#, you can truncate a decimal to int using just explicit casting, e.g.
int seconds = (int) ((dec * 3600) % 60)

Related

Getting Time Remaining

Say something happens at a rate of 5000 per hour and there's some amount remaining (let's say 2500 for example's sake).
How would I get the hours, minutes, and seconds remaining?
I would think it'd be something along the lines of:
hour = floor(remaining / perHour)
mins = floor(remaining % perHour / 60)
secs = floor(remaining % perHour % 60)
However calculating that back up using the below returns the incorrect amount.
time = hour + (mins / 60) + (secs / 60 / 60)
time * perHour // 3472.2 - not 2500
The time should be shorter so I'm obviously calculating this wrong. I would appreciate it if someone were to explain where I went wrong.
EDIT: I'm aware this isn't the Maths SE but the Maths SE is supposed to be for high level maths, and this is the next best fit.
Figured out a method, but it may not be the best so I'll leave this question up for a while longer.
hour = floor(remaining / perHour)
mins = floor(remaining / perHour * 60) - hour * 60
secs = floor(remaining / perHour * 3600) - mins * 60 - hour * 3600
Our question is how much time remains, and we know the rate of the process. No sweat, we establish a rate ( Items/minute, Items/sec) and divide the number of remaining elements by the rate. We could use any unit of time we want as long as we keep it consistent -- personally, I like rates in per-second because Hz.
A Demo
function getRemainingTime(remainingItems) {
const processRatePerHour = 5000;
const processRate = (processRatePerHour / 60 / 60); // 1.3888 per second
remainingSeconds = remainingItems / processRate;
return {
hours: (remainingSeconds / 3600),
minutes: (remainingSeconds / 60),
seconds: remainingSeconds
};
}
function showProgress(remainingItems) {
var time = getRemainingTime(remainingItems);
var list = document.createElement('ul');
var processEnd = moment().add(time.seconds, 's');
list.innerHTML = `
<ul>
<h3> With ${remainingItems} remaining, we will be finished ${processEnd.fromNow()}. </h3>
<li> Hours Remaining: ${time.hours} </li>
<li> Minutes Remaining: ${time.minutes} </li>
<li> Seconds Remaining: ${time.seconds} </li>
</ul>`;
document.body.appendChild(list);
}
// Let's try it out!
showProgress(4999);
showProgress(2500);
showProgress(100);
body {
font-family: 'Helvetica', sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
<h2> Please Accept My Answer v.0.2. </h2>

Seconds to hours, minutes and seconds?

I am very bad at math, but what is the mathematical equation (in its simplest possible form) to convert 3605 seconds to hours, minutes and seconds?
3605 / 60 / 60 = 1,0013888888 hours
Am I on the right track?
time.hours = seconds / 3600;
time.minutes = (seconds - 3600 * time.hours) / 60;
time.seconds = seconds - 3600 * time.hours - 60 * time.minutes;
This doesn't work, but it should, shouldn't it?
Yes, you are on the right track. Here's a breakdown.
3605 secs
60 sec in a minute 3605/60 = 60.083 minutes
60 minutes in an hour 60.083 = 1.001 hour
24 hours in a day 1.001/24 = .0417 of a day
Let t be the total number of seconds
h = int(t / 3600)
m = int((t - 3600 * h) / 60)
s = t - 3600 * h - 60 * m
See code here: http://ideone.com/OzLF8g
1 minute = 60 seconds
1 hour = 60 minutes = 60*60 seconds
So,
if
x = 3605
a = number of hours
b = number of minutes
c = number of seconds
then
a = ⌊ x / (60*60) ⌋
b = ⌊ (x - (a*60*60)) / 60 ⌋
c = x - ((a*60*60) + (b*60))
⌊⌋ means quotient
hours = seconds // 3600
minutes = (seconds // 60) % 60
sec = seconds % 60
try it

Converting angle of circle to time in minutes

I have been trying to develop a clock control with a help of a circle. So if the circle is at 360 degree its 3'O clock, if its 90 degree then it will be 12'o clock. I can't figure out what formula can be used to find the time in hh:mm format if I have the angle of the circle.
eg.
9'o clock is 180 degree.
3'o clock is 360 degree
12'o clock is 90 degree and so on.
There's probably a more concise way to do this, but here's what you need to do.
Calculate the decimal value of the time, using 3 - (1/30) * (angle mod 360)
If the result is less than zero, add 12.
Take the integer portion to use as the hours, replacing a value of zero with 12.
Take the remainder (the decimal portion of the calculation from step 1) and convert to minutes by multiplying by 60.
Format your hours and minutes, padding with leading zeros if less than 10, and combine them with the colon.
An example implementation in java:
public static String convertAngleToTimeString(float angle) {
String time = "";
float decimalValue = 3.0f - (1.0f/30.0f) * (angle % 360);
if (decimalValue < 0)
decimalValue += 12.0f;
int hours = (int)decimalValue;
if (hours == 0)
hours = 12;
time += (hours < 10 ? "0" + hours: hours) + ":";
int minutes = (int)(decimalValue * 60) % 60;
time += minutes < 10 ? "0" + minutes: minutes;
return time;
}
You could check out these formula's on Wikipedia, they might help: http://en.wikipedia.org/wiki/Clock_angle_problem
But other than that, you could do something simple like, degrees/360 * 12. + offset.
For example, if we set that 360 degrees is 12 o'clock, and you had 90 degrees. You would get. 90/360 * 12 = 3. So that would be 3'o clock. Then you could add your offset, which in your case is 3 so it would be 6 o'clock.
First assume 12 o'clock is at 0 degrees. This makes sense because the degrees just increases when going around the clock once, and so does the hours (there's no wrap-around), so maybe we can just multiply the hours by a constant.
To have it reach 360 again at 12 o'clock, we need to multiply the hours by 360/12 = 30.
So now 3 o'clock is at 90 degrees and 12 o'clock is at 0.
Subtract 90 and we have 3 o'clock at 0 and 12 o'clock at -90.
Then make it negative and we have 3 o'clock at 0 and 12 o'clock at 90, as required.
There we go, now you just need to put it all together.
hrs=date +%H #H >>
min=date +%M #min >>
dim=echo "scale=2; $hrs * 60 + $min" | bc #day in minutes >>
dis=echo "scale=2; $dim * 60 + $sec" | bc #day in seconds >>
did=echo "scale=2; $dis / 240" | bc #day in degree >>
The Planet revolution is One degree per 240 seconds.
I work to make a sumerian-time-sys .
One sumerian hour is equivant with two current HRS or 30 revolution-degree. search for sexagesimal systems.
Have fun!

Split down a number in seconds to days, hours, minutes, and seconds?

I've heard that it's possible to accomplish this using the modulus % operator present in most programming languages. The real question is, how? I'm unfamiliar with how modulus works, so I've had difficulties using it in the past. Given the present time here in seconds since 1970, 1307758473.484, how can I calculate how many years that is, days that is, hours that is, and minutes that is using modulus?
I'm essentially looking to format it like this: "5 years, 10 days, 12 hours, 7 minutes, and 18.56 seconds". How would I do this? I'm really interested in learning the logic behind this and not interested in a simple drop-in solution.
When you do integer division, you get quotient and remainder. For example,
5 divided by 3 is quotient 1 with remainder 2.
In programming languages, this is usually expressed as:
5 / 3 # => 1
5 % 3 # => 2
The conversion you want is just a repeatation of this. It's easier to to start from the lower unit and go higher on.
First, you have
1307758473.484 seconds
Since 60 seconds is 1 minute, and
1307758473.484 / 60 = 21795974 (intended to be integer division)
1307758473.484 % 60 = 33.484,
it is the same as
21795974 minutes 33.484 seconds
Since 60 minutes is 1 hour, and
21795974 / 60 = 363266
21795974 % 60 = 14
it is further the same as
363266 hours 14 minutes 33.484 seconds
Now, there is a little bit of difficulty. Most days are 24 hours. When there is a leap second, it is not. If you ignore leap seconds and assume 1 day is 24 hours, then, by doing the calculation,
363266 / 24 = 15136
363266 % 24 = 2
it is further the same as
15136 days 2 hours 14 minutes 33.484 seconds.
Similarly, Most years are 365 days. When there is a leap day (year), it is not. If you ignore leap days and assume that 1 year is 365 days, then by doing the calculation,
15136 / 365 = 41
15136 % 365 = 171
it is further the same as
41 years 171 days 2 hours 14 minutes 33.483 seconds
Modulus returns the remainder when performing integer division.
I think its easiest to understand how to use Mod by working backwards through a problem first.
Lets start simple with hours, minutes and seconds - 1 hour, 10 minutes and 30 seconds to be precise.
First, you have 30 seconds. This is easy - it's just 30. No brainer.
Now add minutes - to determine minutes as seconds you multiply them times 60. Thus 10 minutes and 30 seconds = 630 seconds.
Now we see how mod works - because if you divide 630 by 60 you get 10.5 but if you ignore the fraction (whole integer division) you get 10. The remainder is the seconds.
So if you MOD 630 by 60 you get 30 - the remainder left over when dividing 630 by 30.
So to determine minutes and seconds, divide by 60 for the minutes, and mod by 60 for the seconds.
Now add an hour. One hour = 60 minutes and 60 minutes is 60*60 seconds so 1 hour = 3600 seconds. 3600 + 600 + 30 = 4230 seconds.
4230 / 3600 (1 hour) = 1 - so we have one hour
4230 % (mod) 3600 = 630 - grab this and now we process for minutes.
So if you flesh this out further and add a day - 1 day = 24 hours = 24*3600 = 86400
86400+3600+600+30 = 90630
90630 / 86400 = 1 -> 1 day
90630 % 86400 = 4230 -> seconds left over
4230 / 3600 = 1 -> 1 hour
and repeat the above logic.
Hope that helps clear it up - you keep repeating that iteration further and you can do weeks and years, but months are special since they're irregular, and so are leap years.
Whenever converting from a small base unit (seconds) to a series of larger units (minutes/hours/days/years/decades/centuries/millennia) you can use the modulo (%) operator to keep track of the remaining base units as you extract each large unit.
It is an elegant/simple way to keep a sort of running total in base units. Start extracting BaseUnits with the largest unit you want and work your way back down until you get to the original BaseUnit.
This only works when the extracted unit is nonzero. If it's zero then you have extracted no base units at all and don't need the modulo operator.
It is important to remember that the result of the modulo operation will always be in the original base unit. That can get confusing.
Let's restate 1 million seconds as larger time units. Let 1 year = 31,536,000 seconds and no leap years or other calendar adjustments.
#include <cstdio>
#define SEC2CENT 3153600000
#define SEC2DEC 315360000
#define SEC2YR 31536000
#define SEC2MONTH 2592000
#define SEC2WEEK 604800
#define SEC2DAY 86400
#define SEC2HOUR 3600
#define SEC2MIN 60
main()
{
unsigned int sec = 1000000; //I am 1 million seconds old or...
unsigned int centuries = sec / SEC2CENT;
if (centuries) sec = sec % SEC2CENT; //if nonzero update sec
unsigned int decades = sec / SEC2DEC;
if (decades) sec = sec % SEC2DEC; //the purpose of modulo for units is this running total of base units
unsigned int years = sec / SEC2YR;
if (years) sec = sec % SEC2YR;
unsigned int months = sec / SEC2MONTH;
if (months) sec = sec % SEC2MONTH;
unsigned int weeks = sec / SEC2WEEK;
if (weeks) sec = sec % SEC2WEEK;
unsigned int days = sec / SEC2DAY;
if (days) sec = sec % SEC2DAY;
unsigned int hours = sec / SEC2HOUR;
if (hours) sec = sec % SEC2HOUR;
unsigned int minutes = sec / SEC2MIN;
if (minutes) sec = sec % SEC2MIN;
unsigned int seconds = sec; //seconds should now be less than 60 because of minutes
printf("I am now exactly %u centuries, %u decades, %u years, %u months, %u weeks, %u days, %u hours, %u minutes, %u seconds old and that is very old indeed.", centuries, decades, years, months, weeks, days, hours, minutes, seconds);
}

Convert unix timestamp to julian

How can I convert from a unix timestamp (say 1232559922) to a fractional julian date (2454853.03150).
I found a website ( http://aa.usno.navy.mil/data/docs/JulianDate.php ) that performs a similar calculation but I need to do it programatically.
Solutions can be in C/C++, python, perl, bash, etc...
The Unix epoch (zero-point) is January 1, 1970 GMT. That corresponds to the Julian day of 2440587.5
So, in pseudo-code:
function float getJulianFromUnix( int unixSecs )
{
return ( unixSecs / 86400.0 ) + 2440587.5;
}
I know that this is an old post, but I'll just say ...
The answer given by Jason Cohen is a good approximation of the conversion.
There is a problem though that relates to the number of seconds in one day. A day is not -exactly- 86400 seconds long, and periodically seconds are added to days in order to keep time synchronized with the various observable standards. These are called Leap Seconds (https://en.wikipedia.org/wiki/Leap_second). Leap seconds are added to UTC in order to keep it within 1 second of UT1.
It stands to reason that as more and more time has elapsed since Jan 1, 1970, the simple conversion above will accrue more and more error from "actual observable time." Between 1972 and 2013 there were added 25 leap seconds.
Part of the beauty and the simplicity of Julian Day numbers is that they don't represent date strings at all. They are just a count of elapsed time since the start of the Julian Epoch, much like POSIX time is a continuous count of milliseconds since the POSIX Epoch. The only problem that exists, then, is when you try to map a Julian Day number to a localized date string.
If you need a date string that is accurate to within a minute (in 2013), then you'll need an algorithm that can account for leap seconds.
Here is my JavaScript code to convert Unix timestamp to Julian. Originally is showing the current date and time, but with a little mod is answer to your question:
function computeJulianDate(DD,MM,YY,HR,MN,SC) {
with (Math) {
HR = HR + (MN / 60) + (SC/3600);
GGG = 1;
if (YY <= 1585) GGG = 0;
JD = -1 * floor(7 * (floor((MM + 9) / 12) + YY) / 4);
S = 1;
if ((MM - 9)<0) S=-1;
A = abs(MM - 9);
J1 = floor(YY + S * floor(A / 7));
J1 = -1 * floor((floor(J1 / 100) + 1) * 3 / 4);
JD = JD + floor(275 * MM / 9) + DD + (GGG * J1);
JD = JD + 1721027 + 2 * GGG + 367 * YY - 0.5;
JD = JD + (HR / 24);
}
return JD;
}
function getUTCDateTimeOrJD(now,jd=0) {
var hours = now.getUTCHours();
var minutes = now.getUTCMinutes();
var seconds = now.getUTCSeconds()
var month = now.getUTCMonth() + 1;
var day = now.getUTCDate();
var year = now.getUTCFullYear();
if (jd==1)
return computeJulianDate(month, day, year, hours, minutes, seconds);
else
return day+". "+month+". "+year+". "+hours+":"+minutes+":"+seconds;
}
var unixTime = 1473294606;
getUTCDateTimeOrJD(new Date(unixTime*1000));
getUTCDateTimeOrJD(new Date(unixTime*1000),1);
Working JSFiddle example here
This question was asked over 13 years ago as of writing. That's pretty wild. Thanks to eapo's JS formula I converted it to PineScript v5 and in testing its at least really close. I don't think perfect accuracy would even be relevant for most (if any) TradingView applications. So, I didn't go as far as to ensure perfect accuracy. But it works. Thanks eapo, you saved me a bunch of time.
EDIT: TradingView displays times in the stock/currency exchange time zone. So, it became necessary to create additional arguments to provide for the UTC offsets that exchanges utilize.
[IMPORTANT: Keep in mind that exchanges that utilize daylight savings time will shift from UTC - n to UTC - n - 1 depending on the DST state. You must update your UTC offset argument accordingly.]
// Julian Date & Partial Day in CST
computeJulianDate(dd, mm, yy, hr, mn, sc, offset=0, live=false) =>
HR = hr
HR := hr + (mn / 60) + (sc / 3600)
GGG = 1
if year <= 1585
GGG := 0
float JD = -1 * math.floor(7 * (math.floor((mm + 9) / 12) + yy) / 4)
S = 1
if ((mm - 9)<0)
S :=-1
A = math.abs(mm - 9)
J1 = math.floor(yy + S * math.floor(A / 7))
J1 := -1 * math.floor((math.floor(J1 / 100) + 1) * 3 / 4)
JD := JD + math.floor(275 * mm / 9) + dd + (GGG * J1)
JD := JD + 1721027 + 2 * GGG + 367 * yy
JD := JD + (HR / 24)
barsInSession = timeframe.isintraday ? ((24 * 60) / timeframe.multiplier) : timeframe.multiplier
barsInSession := math.floor(barsInSession) == barsInSession and timeframe.isintraday ? barsInSession - 1 : math.floor(barsInSession)
offsetInc = 1 / barsInSession
offsetCt = (offset * ((barsInSession / 24) * offsetInc))
JD := live ? JD + offsetCt : math.floor(JD - offsetCt) - 0.5
JD

Resources