I have a custom time model with an Integer for hours and an Integer for minutes, seconds.
The class has an AddMinute(int value) method and I want that e.g....
CustomTime myTime = new CustomTime();
myTime.AddMinute(75);
...the minutes are added as Hours += 1 and Minutes += 15.
I have the solution myself, but am currently looking for the shortest possible one that does this
Does anyone know a good one?
For your current class the best answer I think is what René Vogt mentioned in the comments:
Hours += (value + Minutes) / 60;
Minutes = (value + Minutes) % 60;
However I don't see a point in reinventing the wheel, You can use TimeSpan struct instead of your own CustomTime class, which already have all these options, and not only adding seconds, minutes, ... you can add/subtract another time and more:
TimeSpan Struct (Microsoft Docs)
Related
So I run some type of game, and I want to add a command !uptime that displays how long server has been running for since the last open or whatever
This code (from microsoft website) shows the tick count and displays it correctly
int result = Environment.TickCount & Int32.MaxValue;
player.SendMessage("Result: " + result);
but I want to be able to display how long its been up in minutes.
From the MSDN documentation, we can see that Environment.TickCount
Gets the number of milliseconds elapsed since the system started.
You can then convert it to minutes like so:
var minutes = (Environment.TickCount - serverStartTickCount) / 60000; // 1000 ms/s * 60 s/m
Alternatively, you might want to consider storing DateTime.Now when the server starts. Say your class is called Program, you can add this to it:
public static readonly DateTime ServerStartTime = DateTime.Now;
and then do this when the command is run:
var uptime = DateTime.Now - Program.ServerStartTime;
var minutes = uptime.TotalMinutes;
This would allow you to get an accurate uptime when the Environment.TickCount roll over every few weeks, as #Carlos pointed out.
From the reference docs:
A 32-bit signed integer containing the amount of time in milliseconds
that has passed since the last time the computer was started.
So divide by 1000 to get seconds, and then 60 to get minutes.
Note the thing is only 32 bit, so it loops back every few weeks.
Use a TimeSpan.
TimeSpan uptime = TimeSpan.FromMilliseconds(Environment.TickCount);
double totalMinutes = uptime.TotalMinutes;
I'm trying to create a clock for my game. My hours and seconds are both float values so I am using Math.Round to round them off to the nearest whole number. The problem is that the Hours and Seconds variables aren't changing at all. Am I using Math.Round wrong?
public void Update()
{
Hours = (float)Math.Round(Hours, 0);
ClockTime = Hours + ":" + Seconds;
if (Hours >= 24)
Hours = 0;
if (Seconds >= 60)
Seconds = 0;
}
In my update method for my day/night class.
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
clock.Hours += (float)elapsed;
clock.Update();
When I print the numbers on the screen, nothing is changing. If I take away the (float) cast to the Math.Round I get an error cannot convert double to float.
Don't use floating point in this case, there's absolutely no reason for an hour, minute or second to be non-integral.
What's almost certainly happening is that you're ending up with a float value like 59.9999 despite the fact you think you're rounding it.
There are real dangers in assuming floating point values have more precision than they actually do.
If you hold your number of seconds in an unsigned integral 32-bit type, you can represent elapsed time from now until about the year 2150 AD, should anyone still be playing your game at that point :-)
Then you simply use integer calculations to work out hours and seconds (assuming you're not interested in minutes as seems to be the case), pseudo-code such as:
hours = elapsed_secs / 3600
secs = elapsed_secs % 3600
print hours ":" seconds
Beyond that advice, what you're doing seems a tad strange. You are adding an elapsed seconds field (which I assume you're checked isn't always set to zero) to the hours variable. That's going to make gameplay a little difficult as time speeds by at three and a half thousand times its normal rate.
Actually, you should used DateTime to track your time and use the DateTime properties to get the hours and seconds correctly instead trying it yourself using float for seconds and hours. DateTime is long based and supports from fractions of milliseconds to millenias and of course seconds. It has all the functions built in to add milliseconds or years or seconds or ... correctly, which is actually rather difficult.
Out Time :
2013-03-08 15:00:00.000
In Time :
2013-03-08 11:21:03.290
I need to get Hours and Minutes separately for same date from above, when (Out Time - In Time).
How can I do that ?
I think you probably just want:
TimeSpan difference = outTime - inTime;
int hours = (int) difference.TotalHours;
int minutes = difference.Minutes;
Note that Minutes will give you "just the minutes (never more than 59)" whereas TotalHours (truncated towards zero) will give you "the total number of hours" which might be more than 23 if the times are more than a day apart.
You should also consider what you want to do if the values are negative - either consider it, or explicitly rule it out by validating against it.
The Subtract method on the DateTime class will allow you subtract that date from the other date.
It will give you a TimeSpan which will be the difference.
I'll leave it to you to work out the actual code.
http://msdn.microsoft.com/en-GB/library/8ysw4sby.aspx
You can use Hours property and Minutes
link : http://msdn.microsoft.com/en-us/library/system.datetime.hour.aspx
The following code
Console.WriteLine("{0:%h} hours {0:%m} minutes",
new TimeSpan(TimeSpan.TicksPerDay));
produces this output:
0 hours 0 minutes
What I would like is this output:
24 hours 0 minutes
What am I missing in this format string?
P.S. I know that I could manually bust up the TimeSpan into days and hours, and multiply the two but would rather use a custom format string, as these timespans are being displayed in a silverlight datagrid and people are expecting to see horus, not days.
According to MSDN, using %h will show you
The number of whole hours in the time interval that are not counted as part of days.
I think you will need to use the TotalHours property of the TimeSpan class like:
TimeSpan day= new TimeSpan(TimeSpan.TicksPerDay);
Console.WriteLine("{0} hours {1} minutes", (int)day.TotalHours, day.Minutes);
Update
If you absolutely need to be able to achieve the stated format by passing custom formatters to the ToString method, you will probably need to create your own CustomTimeSpan class. Unfortunately, you cannot inherit from a struct, so you will have to build it from the ground up.
There doesn't seem to be a format option for getting the total hours out of a TimeSpan. Your best bet would be to use the TotalHours property instead:
var mySpan = new TimeSpan(TimeSpan.TicksPerDay);
Console.WriteLine("{0} hours {1} minutes", (int)mySpan.TotalHours, mySpan.Minutes);
TotalHours returns a double as it includes the fractional hours so you need to truncate it to just the integer part.
Another possibility is:
TimeSpan day = new TimeSpan(2,1,20,0); // 2.01:20:00
Console.WriteLine("{0} hours {1} minutes", (int)day.TotalHours, day.Minutes);
Console will show:
49 hours 20 minutes
I have this DateTime object (update) which is set to DateTime.now, when i update my application.
I also have this timerTick event, called on every 5 seconds which should check how many minutes ago, update was.
I've tried with:
if ((DateTime.Now - Updated).Minutes > 0)
{
updateTextBlock.Text = "updated " + ((DateTime.Now - Updated).Minutes).ToString() + " minutes ago";
}
But it does not seem to work correctly. Isn't there a better way to do this?
/R
I suspect you want TotalMinutes instead of Minutes. Otherwise you'll only ever get a value in the range -59 to 59.
You may also want to consider using UtcNow instead of Now - otherwise you could get odd effects due to time zone changes (either the user changing time zone, or the time zone changing its UTC offset, usually for daylight saving time.)
You may find it easier to use an instance of System.Diagnostics.StopWatch to keep track of how much time has elapsed since any particular starting point.
It can be more reliable and accurate than doing math on DateTime objects because it'll use the hardware's High Resolution Timer if one is available.
You're probably looking for TotalMinutes, not just Minutes. TotalMinutes will give you the total number of minutes in the interval, whereas Minutes only gives 0-59 (since you also have Hours, etc.)
One way I did something similar was using TimeSpan
I had two variables timePassed and tickTime
where I would set tickTime to be a 5 second TimeSpan and timePassed to be 0
TimeSpan tickTime = new TimeSpan(0,0,0,5); // 5 seconds
TimeSpan timePassed = new TimeSpan(0,0,0,0); // 0 seconds
then in the handler for the tick event I would add tickTime to timePassed
timePassed = timePassed.Add(tickTime); \\ adds 5 seconds to the timePassed TimeSpan
Then you can use timePassed to get the time since update.
Hope this helps