I may be being really stupid here, but my brain's gone blank.
I've got a slider bar (which uses Int32 values) but I want to use it to select a position in a music song (mm.ss)
I also want to output the value that the slider is displaying in to a label above it, so it's easier to see what the slider is set to.
Anyone have any suggestions?
I thought of trying to convert the int value in to a decimal then dividing by 60.
I'm doing this in C# by the way.
What does the int value represent? If it's the number of seconds through the song, you should use:
TimeSpan time = TimeSpan.FromSeconds(seconds);
string text = time.ToString(#"mm\.ss");
Using a decimal would be a really bad idea - a format with a number of seconds isn't the same as a fractional number of minutes. For example, 10.50 minutes as a fractional number of minutes is 10 minutes and 30 seconds, not 10 minutes and 50 seconds, which is what you want as far as I can tell.
TimeSpan is the natural way of representing a time duration in .NET... which is why that's the type which supports formatting in minutes and seconds.
Converting it into decimal would not display it the way that you want it. For example four and an half minute would display as 4:50, not 4:30.
Divide the time into minutes and seconds, and format them:
int minutes = time / 60;
int seconds = time % 60;
string formatted = minutes.ToString() + ":" + seconds.ToString("00");
You should represent the length of the song internally as seconds (which can be saved in an int). To actually display it, you do song_length / 60 to get the minutes (this is called integer division, it returns the result and discards the fraction, e.g. 100/60 = 1).
After that, you can get the seconds by song_length % 60 (% is the modulo operator).
Edit: didn't see the c# tag. Jon Skeet's answer is more appropiate in c#.
Edit: I misunderstood the scope of the question, but I'll leave this in case it's helpful.
Store the total length of the track in seconds.
Calculate the position of the slider as a fraction of the maximum possible slider value.
Multiply the track length (in seconds) with fractional value obtained in 2). This gives the offset from the start of the track in seconds.
Format the value from 3) for display.
Here is a contrived example to illustrate the process:
int maxSliderValue = 100;
int sliderValue = 18;
int trackLengthInSeconds = 248;
float sliderFraction = ((float)sliderValue)/((float)maxSliderValue);
int offsetInSeconds = Convert.ToInt32(Math.Floor(trackLengthInSeconds * sliderFraction));
TimeSpan offset = TimeSpan.FromSeconds(offsetInSeconds);
string displayValue = offset.ToString(#"mm\.ss");
Related
I have a Timespan that is always in milliseconds, but I need to show the date in minutes and seconds only so that it's always "mm:ss". Even if there are hours in the timespan, the output string should contain only minutes and seconds.
For example, if there is a timespan of 02:40:30, it should get converted to 160:30.
Is there a way to achieve this?
Reed's answer is ALMOST correct, but not quite. For example, if timespan is 00:01:59, Reed's solution outputs "2:59" due to rounding by the F0 numeric format. Here's the correct implementation:
string output = string.Format("{0}:{1:00}",
(int)timespan.TotalMinutes, // <== Note the casting to int.
timespan.Seconds);
In C# 6, you can use string interpolation to reduce code:
var output = $"{(int)timespan.TotalMinutes}:{timespan.Seconds:00}";
You can format this yourself using the standard numeric format strings:
string output = string.Format("{0}:{1}", (int)timespan.TotalMinutes, timespan.Seconds);
I do it this way
timespan.ToString("mm\\:ss");
That is a pretty basic math problem.
Divide by 1000 to get total number of seconds.
Divide by 60 to get number of minutes.
Total seconds - (minutes * 60) = remaining seconds.
I have a integer number say Int64 i. the data in this variable is both in minute format and seconds format. Ho can identify the integer number is in munutes or in seconds
suppose,
Int64 i = 0;
now values may be..(For date 2016-02-18 00:00:00:000)
i = 1140220800; //(value is in seconds)
//or
i = 19003680; //(value is in minutes i.e. 1140220800/60)
No how to identify data is in minutes or seconds ?
Well you could just assume that if the number if smaller than some threshold value which makes sense in your context then it's minutes, else it's seconds. For example:
int number = 19003680;
if(number < 42076800) // 2050-01-01 in minutes, 1971-03-05 in seconds.
{
// minutes
}
else
{
// seconds
}
However, this question goes against the principles of good programming - one variable should only have one meaning. If a variable can represent both seconds and minutes, there's a problem in the design of your data.
EDIT:
If you can't reasonably fence your data to where seconds and minutes don't overlap - that is, if you can have both large dates represented in seconds, and small dates represented in minutes, then sadly it's impossible to differentiate between the two.
This code
(this.ApprovedDate - this.ReceivedDate).TotalDays
gives me a double typed value.
How do I get the integer one rounded up? Assuming that this.ApprovedDate and this.ReceivedDate are both DateTime type.
You need to use the Math library and cast to int.
Example:
var a = new TimeSpan(5, 14, 0, 0); // 5 days, 14 hours
var x = a.Days; // Does not round up. = 5
var y = (int) Math.Round(a.TotalDays); // Rounds up. = 6
TotalDays gets the value of the current TimeSpan structure expressed in whole and fractional days. Instead you should be using the integer Days property which gets the days component of the time interval represented by the current TimeSpan structure, see the documentation.
Please note that using Days gives the whole number of days between two dates and will ignore fractions. Depending on your requirements you may want to round TotalDays to zero digits instead and cast it to an integer as proposed by MutantNinjaCodeMonkey.
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.
Consider you have 2 dates:
var left = new DateTime(2012,10,05,13,30,00);
var right = new DateTime(2012,10,05,13,31,30);
The fact is: right is 1,5 minutes more than left. If we talk in terms of MINUTES, it seems to me right is around 5% more than left DateTime. (As year,month,date,hour are EQUAL in between. But can be different as well.)
How can I calculate the that right is how much percent more or less than the left date, in terms of minutes?
You can get the difference in minutes like this:
double difference = TimeSpan.FromTicks(right.Ticks).TotalMinutes -
TimeSpan.FromTicks(left.Ticks).TotalMinutes;
You could do the following but I don't think the result would be very useful in displaying difference between two dates:
double percent = TimeSpan.FromTicks(right.Ticks).TotalMinutes /
TimeSpan.FromTicks(left.Ticks).TotalMinutes *
100 - 100;