Simple way to change 180 to 03:00 - c#

Hey! I am trying to change a number of seconds in to a proper time stamp format.
Like I do this to change 180 to 03:00
private void writeTime(int tempo)
{
TimeSpan otempo = new TimeSpan(0, 0, tempo);
string minutos = ((otempo.Minutes <= 9) ? "0" : "") + otempo.Minutes.ToString();
string segundos = ((otempo.Seconds <= 9) ? "0" : "") + otempo.Seconds.ToString();
label1.Text = minutos + ":" + segundos;
centrarLabel();
}
This does give me 180 into a proper format. I just want to know if there is a simpler way.
This function might be called many many times and I don't want to create a new instance of TimeSpan every single time as I think this might pose a problem with memory etc. I tried using the DateTime class but... I just simply don't see how I can pass it the seconds and it gives me the proper format :(
I am not that great with c#. I am really trying to learn :)
Thanks

use
label.Text = string.Format("{0:d2}:{1:d2}", otempo.Minutes, otempo.Seconds);
You can use oTempo.TotalMinutes if your minute count can grow bigger that 60...
And don't forget to specify a culture also.

TimeSpan t = TimeSpan.FromSeconds(180);
string s = String.Format("{0:00}:{1:00}", t.Hours, t.Seconds);

int tempo = 180;
TimeSpan time = TimeSpan.FromSeconds(tempo);
string txt = string.Format(
"{0:00}:{1:00}", time.Minutes, time.Seconds);
(edit) As has already been observed - there are no immediate memory concerns with TimeSpan, since it is a struct. However, if you want to be paranoid:
int tempo = 180;
string txt = new StringBuilder(5)
.Append((tempo / 60).ToString().PadLeft(2, '0')).Append(':')
.Append((tempo % 60).ToString().PadLeft(2, '0')).ToString();

TimeSpan is a struct, it is (in this case) allocated on the stack so the cost it negligible, especially considering that you have to make at least one string allocation anyway which is the expensive part.
TimeSpan.FromSeconds(tempo).ToString();
should be sufficient for your needs so long as 180 seconds -> "00:03:00" is acceptable

Like others have mentioned, there's probably no need to worry about creating a new TimeSpan to do the conversion, but the simplest way to format it without creating any temporary objects is this:
String.Format("{0:00}:{1:00}", tempo / 60, tempo % 60)

Related

Predicting process end time

I have a simple problem that I'm having more trouble with than I should.
It's pretty straight forward: I have a time the process started _startTime, and the current time. I also have the total number of records I need to process _records, and the current record number _current.
How can I get a simple linear prediction of the end time? I've ended up in a rabbit hole of differencing ticks and stuff, but I imagine there's some simple DateTime or TimeSpan trickery I could be using,
TimeSpan delta = DateTime.Now - _startTime;
float progress = (float)_records / (float)_current;
hmm really sounds much simpler than it is probably
TimeSpan timeTakenSoFar = DateTime.Now - _startTime;
double percentageDoneSoFar = (double)_current / (double)_records;
TimeSpan timeTakingInTotal = timeTakenSoFar / percentageDoneSoFar;
DateTime finishTime = _startTime.Add(timeTakingInTotal);
This should work.
Update:
According to MSDN you cannot divide TimeSpan, but in that case you can use ticks: (I don't have a C# compiler at hand to check if it's 100% syntactically correct)
TimeSpan timeTakenSoFar = DateTime.Now - _startTime;
double percentageDoneSoFar = (double)_current / (double)_records;
double timeTakingInTotalInTicks = timeTakenSoFar.Ticks / percentageDoneSoFar;
DateTime finishTime = _startTime.AddTicks((long)timeTakingInTotal);
Take a sample every few cycles, and determine how long they took from start time.
now.subtract(_startTtime)
Divide that by the _current pointer, and get the time per cycle.
Multiple the time/cycle with ((_records - _current) <- cycles you have left to do)
The higher your "sample" resolution, the more accurate your result... but it is still just a prediction.
var restRecords = _records - _current;
var averageTimeForRecord = delta.TotalMilliseconds / _current;
var restTime = restRecords * averageTimeForRecord;
var finishDate = DateTime.Now.AddMilliseconds(restTime);
Maybe that is what you need?

Converting a double to a time that makes sense

Basically I am setting a limit of hours a user can use. Now every time a button is press, whatever time that person accrued gets taken away from this total value.
However because a limit would be represented as say 156 hours, and the datetime representation of 5 minutes would be 00.05 the result would be 155.95, rather than 155.55 .
I work this out like so
string date2 = TotalMonthlyHours.ToString("HH.mm");
double date = double.Parse(date2);
RunningTotal = date + RunningTotal;
Total = limit - RunningTotal;
Any ideas?
I think you are trying to represent 5 minutes as 0.05. The way to do that is to first of all obtain the minutes as an integer. And then simply convert to double.
double floatmins = minutes/100.0;
And you convert in the other direction like this:
int minutes = (int) (floatmins*100.0);
However, I urge you not to go any further with this. You cannot expect to perform arithmetic on a quantity like that. What is the result of 2.20-1.50? You and I know it's 30 minutes, but the computer says 0.70 which is no use at all.
Store the hours using a true fractional representation. So 5 minutes is 5/60.0. Or store the total minutes in an integer. Or total seconds in an integer. Or a TimeSpan.
The key is that you can write your own helper routines to convert from a sane storage format to a value that is human readable. But you must store the raw data in a representation that will admit arithmetic operations.
I think I worked it out by doing something like this
string[] times = date.ToString().Split('.');
if (date != 0.0)
{
string minutesString = times[1];
string hoursString = times[0];
double minutes = Convert.ToDouble(minutesString);
double hours = Convert.ToDouble(hoursString);
// end of splitting
TimeSpan Limit = TimeSpan.FromHours(limit);
TimeSpan Hours = TimeSpan.FromHours((int)hours);
TimeSpan Minutes = TimeSpan.FromMinutes((int)minutes);
TimeSpan SubTotal = Hours + Minutes;
Time = Limit - SubTotal;
}
Edit: Glad you came up with the same as me,Just read your reply David, let's hope it works
I would convert it to minutes first than add as minutes to the date
var min = Convert.ToDouble(Convert.ToDecimal(textbox.Text) * 60);
DateTimePickerEnd.DbSelectedDate = e.NewDate.Value.AddMinutes(min);

How can I segregate properties of DateTime?

I would like to write: if the result of the difference of 2 DateTimes is longer than 3 hours then.... stuff in the if statement happens. But I only need properties in seconds or minutes, can I extract just that from the DateTime object?
if(diffResult > DateTime.Hour(3))
{
}
I also want to know if its possible to divide DateTime by periods. Say I want to split my diffResult (which is the difference between 2 DateTimes) into 3 periods or perhaps for every 3 seconds my counter gets one added to it.
For the first part:
You can subtract two DateTimes to get a TimeSpan there you can get the total of various units - for example:
if ( (secondTime - firstTime).TotalMinutes > 180.0) ...
or you could use TimeSpan directly:
if (secondTime - firstTime > TimeSpan.FromHours(3)) ...
for the secondpart you have to do some calculation yourself:
var diff = secondTime - firstTime;
var period = TimeSpan.FromSeconds(diff.TotalSeconds / 3.0);
for (var time = firstTime; time < secondTime; time += period)
{ /* do your stuff */ }
U can compare using the follow code:
DateTime dt = new DateTime();
dt = DateTime.Now;
dt.AddHours(3);
int h = (int)DateTime.Now.Hour;
if (dt.Hour == h )
//Do something
else
//do otherthing
You can do this:
TimeSpan time = new TimeSpan(3, 0, 0);
if (date1.Subtract(date2) > time)
{
//YourCode
}
For the second, this article should be useful:
http://www.blackwasp.co.uk/TimespanMultiplication.aspx
The methods your asking about return integer results. What exactly is your question? DateTime.Hour(3) would not even compile.
I think you are looking for DateTime.Now.AddHours(3.0)
I should be clear, the only reason this answer is this sparse, is because of the invalid code in the author's question which. Since I don't attempt to guess at what people actually want, its up to the author, to clarify what he wants exactly.
All he has to do is subtract two DateTime values and compare it to a TimeSpan

MMMMMMSS what kind of a time duration format is this?

i have a file which states duration for a particular event in format MMMMMMSS.Does any one know what kind of format is this for time duration and how to convert it into seconds.I'm using C# language
If the format is really M...MSS (supplied as an integer value), converting it to seconds is quite easy:
var seconds = (value / 100) * 60 + (value % 100);
Why does it work?
value / 100 removes the last two digits (integer division), thus returning MMMMMM, and
value % 100 returns the last two digits (modulo), i.e., SS.
The remainder of the formula is MMMMMM * 60 + SS, which should be pretty self-explanatory.
My guess based on the format is that it could hold a maximum value of 99999959, which would mean 999999 minutes and 59 seconds. But that is pure conjecture, and some sample data would help to bolster this idea. You may never know for certain though.
You should at least be able to determine whether the SS part ever exceeds 59 or not, which would be very important to know.
var input = "02345612";
int minutes = int.Parse(input.Substring(0, 6));
int seconds = int.Parse(input.Substring(6, 2));
int totalSeconds = minutes * 60 + seconds;

Convert DateTime.Now to Seconds

I am trying to write a function that will convert a DateTime.Now instance to the number of seconds it represents so that I can compare that to another DateTime instance. Here is what I currently have:
public static int convertDateTimeToSeconds(DateTime dateTimeToConvert)
{
int secsInAMin = 60;
int secsInAnHour = 60 * secsInAMin;
int secsInADay = 24 * secsInAnHour;
double secsInAYear = (int)365.25 * secsInADay;
int totalSeconds = (int)(dateTimeToConvert.Year * secsInAYear) +
(dateTimeToConvert.DayOfYear * secsInADay) +
(dateTimeToConvert.Hour * secsInAnHour) +
(dateTimeToConvert.Minute * secsInAMin) +
dateTimeToConvert.Second;
return totalSeconds;
}
I realize that I am truncating the calculation for seconds in a year, but I don't need my calculation to be precise. I'm really looking to know if the method that I am using to calculate seconds is correct.
Does anyone have anything that could better compute seconds given from a DateTime object?
Also, Should the return type be int64 if I am coding in C# if I am going to calculate all the seconds since 0 AD?
The DateTime type supports comparison operators:
if (dateTimeA > dateTimeB)
{
...
This also works for DateTime values returned by DateTime.AddSeconds:
if (dateTimeA.AddSeconds(42) > dateTimeB)
{
...
If you really want the number of seconds that elapsed since 01/01/0001 00:00:00, you can calculate the difference between the two DateTime values. The resulting TimeSpan value has a TotalSeconds property:
double result = DateTime.Now.Subtract(DateTime.MinValue).TotalSeconds;
It really doesn't make sense to convert a DateTime object to seconds. Seconds only make sense if you are dealing with a length of time (TimeSpan). Should you want to compare two dates to get the number of seconds between them:
TimeSpan diff = DateTime.Now - PreviousDateTime;
double seconds = diff.TotalSeconds;
If the purpose is finding the number of seconds between two dates, you'd be much better off using the TimeSpan object.
TimeSpan span = date2 - date1;
double seconds = span.TotalSeconds;
See suggestion from thread below:
How do I convert ticks to minutes?
TimeSpan.FromTicks(DateTime.Now.Ticks).TotalSeconds;
Assuming you really need to get at the seconds for the datetime object, you could directly get the "Ticks" property from it. These aren't in seconds but you can easily divide by the proper factor to convert the Ticks to seconds.
See: http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx
So, something like:
DateTime.Now.Ticks/TimeSpan.TicksPerSecond
If you want to compare 2 DateTime object, why just not use the provided operators?
http://msdn.microsoft.com/en-us/library/aa326723%28v=VS.71%29.aspx
DateTime a, b;
if (a > b) //a is after b
I would use the TimeSpan class to get the exact difference between two DateTime instances. Here is an example:
DateTime dt1 = DateTime.Now;
DateTime dt2 = new DateTime(2003,4,15);
TimeSpan ts = dt1.Subtract(dt2);
Once the TimeSpan value (ts, in the code snippet above) is available, you can examine its values to correctly convert the TimeSpan to a given number of seconds.
Using a TimeSpan to get the elapsed time between two DateTimes is probably the best way to go but if you really want to get the number of seconds for a given DateTime you could do something like the following:
DateTime dateTimeToConvert = DateTime.Now;
TimeSpan tsElapsed = dateTimeToConvert - DateTime.MinValue;
return tsElapsed.TotalSeconds;
Note that tsElapsed.TotalSeconds is a Double, not an Int.
Do note that the goal is to get the number of seconds since DateTime.MinVal (the first day of the calendar). I say this, because I see all of these answers for "you do time comparisons like this... add in the object, multiply by that object and do cross-calculus on them, divide by the quotient of the summed result, and Boom! not what you asked."
There's a really simple answer here. Ticks are 100-nanosecond increments. DateTime object.Ticks is the number of ticks that have occurred since 1/1/0001. Ie, year zero. There are 10 million nanoseconds in a second. so...
public static long convertDateTimeToSeconds(DateTime dateTimeToConvert) {
// According to Wikipedia, there are 10,000,000 ticks in a second, and Now.Ticks is the span since 1/1/0001.
long NumSeconds= dateTimeToConvert.Ticks / 10000000;
return NumSeconds;
}

Categories