Convert 60 or more minutes to hours - c#

I have two variables that hold hours and minutes. I want to round off the time if the minutes variable is = 60 minutes.
So if hours = 3, minutes = 60, I want to return hours = 4, and minutes = 00. Is there a time function for this?

Try this (assuming both hours and minutes are int):
hours += minutes / 60;
minutes %= 60;

This is really trivial to implement:
while (minutes >= 60)
{
minutes -= 60;
hours += 1;
}

Create own struct/class to store time with custom getter/setter
for example
struct myTimeStruct
{
public int minutes
{
get { return minutes; }
set
{
minutes = minutes % 60;
hours += minutes / 60;
}
}
private int hours
{
get { return hours; }
set { hours = value; }
}
}

Take a look at the TimeSpan class:
var hours = 3;
var minutes = 60;
var timeSpan = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes);
var totalHours = timeSpan.TotalHours;

Related

How do I update my in-game timer to only start adding the minute counter once it reaches 60 seconds (i.e. 34 instead of 00:34)?

I only want the numbers to change to minutes:seconds once a minute has been reached. Before that I just want the seconds. My timer is currently set up as follows:
time += Time.deltaTime;
string minutes = Mathf.Floor(time / 60).ToString("00");
string seconds = Mathf.RoundToInt(time % 60).ToString("00");
gameTime.text = string.Format("{0}:{1}", minutes, seconds);
Fix your code like this:
time += Time.deltaTime;
string minutes = Mathf.Floor(time / 60).ToString("00");
string seconds = Mathf.RoundToInt(time % 60).ToString("00");
if (time >= 60){
gameTime.text = string.Format("{0}:{1}", minutes, seconds);
}
else
{
gameTime.text = seconds;
}
Well without magic but simple straight forward you could do
var minutes = Mathf.FloorToInt(time / 60f);
var seconds = Mathf.RoundToInt(time % 60f);
if(minutes > 0)
{
gameTime.text = $"{minutes:00}:{seconds:00}";
}
else
{
gameTime.text = $"{seconds:00}";
}

How to write a method to get a value in seconds and print in Hours, Minutes and Seconds

Ok, so this was my first question on StackOverflow, I see the comments haven't been great (and the post keeps getting deleted before I have had a chance to fix it). Give me a chance! My understanding was the question should be as direct as possible and not create 'discussions'?
This is what I have tried already, but the output is not what I expect
int secondsToHours(seconds) {
int totalSec = seconds;
int hrs = totalSec % 3600;
int secs = totalSec % 60;
int mins = totalSec / 60;
string result = hrs + ":" + mins + ":" + secs;
Console.WriteLine(result);
Console.ReadLine();
}
You can use TimeSpan struct:
TimeSpan ts = TimeSpan.FromSeconds(seconds);
And then build string you want:
ts.ToString(#"hh\:mm\:ss")
Look at the TimeSpan class
TimeSpan span = TimeSpan.FromSeconds(total seconds here);
Then look at the Days, Hours, Minutes and Seconds properties, or the TotalDays, TotalHours etc
Well, you could use a TimeSpan object
int seconds = 104700;
TimeSpan ts = new TimeSpan(0, 0, seconds);
Console.WriteLine("Days:" + ts.Days +
", Hours:" + ts.Hours +
", Minutes:" + ts.Minutes +
", Seconds:" + ts.Seconds );
You need to subtract from totalSec. For 4700 as example;
int left;
int hrs = totalSec / 3600; // hrs will be 1
left = totalSec - hrs * 3600; //left will be 1100
int mins = left / 60; //mins will be 18
left = left - mins * 60; // left will be 20
int secs = left; // secs will be 20
As a solution, 4700 will be 1 hours, 18 minutes and 20 seconds.
But using TimeSpan properties would be better such a case. You can use TimeSpan(Int32, Int32, Int32) constructor like;
TimeSpan ts = new TimeSpan(0, 0, seconds);
int hrs = ts.Hours; // 1
int mins = ts.Minutes; // 18
int secs = ts.Seconds; // 20
Simplest way would be using TimeSpan as already suggested in previous answer but also you could try this if you want to do it using Math:
private static void secondsToHours(int seconds)
{
int hrs = seconds / 3600;
int remainder = seconds % 3600;
int mins = remainder / 60;
int secs = seconds % 60;
string result = hrs + ":" + mins + ":" + secs;
Console.WriteLine(result);
Console.ReadLine();
}

Convert TimeSpan to float

How do I convert a TimeSpan to a float , taking into account all of the processing unit (hour minute) for example
if (unit = hour)
convert TimeSpan to a float hours
In another context, is there not a data type "Timespan" in SQL Server ?
Use the Total* properties on TimeSpan, e.g. TimeSpan.TotalHours.
Example for minutes:
var t = new TimeSpan();
var total = t.TotalMinutes;
You can do something like this
TimeSpan elapsedTime = new TimeSpan(125000);
float floatTimeSpan;
int seconds, milliseconds;
seconds = elapsedTime.Seconds;
milliseconds = elapsedTime.Milliseconds;
floatTimeSpan = (float)seconds + ((float)milliseconds / 1000);
Console.WriteLine("Time Span: {0}", floatTimeSpan);
The program output looks like this:
Time Span: 0.012
internal static string TimeSpanToDouble(TimeSpan timeSpan, string unit)
{
double result = 0;
if (unit.Equals("MINUTES"))
result = timeSpan.TotalMinutes;
else if (unit.Equals("HOURS"))
result = timeSpan.TotalHours;
else if (unit.Equals("DAYS"))
result = timeSpan.TotalHours / 24;
else
throw new Exception();
return Convert.ToString(result);
}
You can use Convert.ToSingle, like this:
var ts = new Timespan(0, 1, 1, 30);
var minutes = Convert.ToSingle(ts.TotalMinutes);
var hours = Convert.ToSingle(ts.TotalHours);
The resulting minutes and hours will be, respectively, 61.5 and 1.025
Check out this dotnetfiddle: https://dotnetfiddle.net/uSQfk0
double TsToHoursDouble(TimeSpan ts) => ts.TotalMinutes / 60;
double TsToMinsDouble(TimeSpan ts) => ts.TotalMinutes;
using:
var hrs = TsToHoursDouble(someTimeSpan);
if you need more accurate results, you can use TotalSeconds in such calculations

How to calculate remaining minutes to "next" half an hour or hour?

I would like to calculate the remaining minutes to the "next" half an hour or hour.
Say i get a start time string of 07:15, i want it to calculate the remaining minutes to the nearest half an hour (07:30).
That would be 15min.
Then i can also have an instance where the start time can be 07:45 and i want it to calculate the remaining minutes to the nearest hour (08:00).
That would also be 15min.
So any string less then 30min in a hour would calculate to the nearest half an hour (..:30) and any string over 30min would calculate to the nearest hour (..:00).
I don't want to do a bunch of if statements, because i get from time strings that can start from and minute in an hour.
This is what i do not want to do:
if (int.Parse(fromTimeString.Right(2)) < 30)
{
//Do Calculation
}
else
{
//Do Calculation
}
public static string Right(this String stringValue, int noOfCharacters)
{
string result = null;
if (stringValue.Length >= noOfCharacters)
{
result = stringValue.Substring(stringValue.Length - noOfCharacters, noOfCharacters);
}
else
{
result = "";
}
return result;
}
Is there not an easier way with linq or with the DateTime class
Use modulo operator % with 30. Your result will be equal to (60 - currentMinutes) % 30. About LINQ its used for collections so i can't realy see how it can be used in your case.
You can use this DateTime tick-round approach to get the timespan until next half hour:
var minutes = 30;
var now = DateTime.Now;
var ticksMin = TimeSpan.FromMinutes(minutes).Ticks;
DateTime rounded = new DateTime(((now.Ticks + (ticksMin/2)) / ticksMin) * ticksMin);
var diff=rounded-now;
var minUntilNext = diff.TotalMinutes > 0 ? diff.TotalMinutes : minutes + diff.TotalMinutes;
var minutesToNextHalfHour = (60 - yourDateTimeVariable.Minutes) % 30;
This should do it:
int remainingMinutes = (current.Minute >= 30)
? 60 - current.Minute
: 30 - current.Minute;
var hhmm = fromTimeString.Split(':');
var mins = int.Parse(hhmm[1]);
var remainingMins = (60 - mins) % 30;
var str = "7:16";
var datetime = DateTime.ParseExact(str, "h:mm", new CultureInfo("en-US"));
var minutesPastHalfHour = datetime.Minute % 30;
var minutesBeforeHalfHour = 30 - minutesPastHalfHour;
I would use modulo + TimeSpan.TryParse:
public static int ComputeTime(string time)
{
TimeSpan ts;
if (TimeSpan.TryParse(time, out ts))
{
return (60 - ts.Minutes) % 30;
}
throw new ArgumentException("Time is not valid", "time");
}
private static void Main(string[] args)
{
string test1 = "7:27";
string test2 = "7:42";
Console.WriteLine(ComputeTime(test1));
Console.WriteLine(ComputeTime(test2));
Console.ReadLine();
}

create a time based on seconds in c#

If i have a seconds as a int like 70 80 or 2500 how do i show it as a time of format hh:mm:ss using the most easiest way. I know i can make a separate method for it and i did but i wanna check if there is any lib func already available for it.
THis is the method i created and it works.
private void MakeTime(int seconds)
{
int min = 0;
int sec = seconds;
int hrs = 0;
if (seconds > 59)
{
min = seconds / 60;
sec = seconds % 60;
}
if (min > 59)
{
hrs = min / 60;
min = min % 60;
}
string a = string.Format("{0:00}:{1:00}:{2:00}", hrs, min, sec);
}
This is the function i am using now. it works but still i have a feeling that a single line call will do this. Any one know of any?
You can use TimeSpan
TimeSpan t = TimeSpan.FromSeconds(seconds);
and
use t.Hours, t.Minutes and t.Seconds to format the string how ever you want.
TimeSpan.FromSeconds(seconds).ToString("hh:mm:ss")
Try this:
TimeSpan t = TimeSpan.FromSeconds(seconds);
string a = string.Format("{0:00}:{1:00}:{2:00}", t.Hours, t.Minutes, t.Seconds);
TimeSpan ts = TimeSpan.FromSeconds(666);
string time = ts.ToString();
Use a TimeSpan:
TimeSpan ts = TimeSpan.FromSeconds(70);
Any reason why you can't just use DateTime instead, like this?
DateTime t = new DateTime(0);
Console.WriteLine("Enter # of seconds");
string userSeconds = Console.ReadLine();
t = t.AddSeconds(Int32.Parse(userSeconds));
Console.WriteLine("As HH:MM:SS = {0}:{1}:{2}", t.Hour, t.Minute, t.Second);

Categories