How show minutes and seconds with Stopwatch() - c#

I need to show also the minutes, actually I use this code for show the seconds, but also need the minutes
TimeSpan ts = stopwatch.Elapsed;
Console.WriteLine("File Generated: " + _writer.getBinaryFileName(filePath, Convert.ToInt32(logSelected)) + " in " + "{0}.{1:D2}" + "seconds",
ts.Seconds,
ts.Milliseconds/10 + "\n"
);
how can I do?

You should use:
ts.ToString("mm\\:ss\\.ff")
this will give you minutes, seconds and the hundredths of a second in a time interval.
also take a look at http://msdn.microsoft.com/en-us/library/ee372287.aspx
EDITED:
well if you want minutes be your biggest unit you can do the following:
string.Format("{0}:{1}", Math.Floor(ts.TotalMinutes), ts.ToString("ss\\.ff"))

The TimeSpan.ToString() method in .NET 4.0 has an overload that lets you specify the format.
To display minutes and seconds:
TimeSpan elapsed = GetElapsedTime(); // however you get the amount of time elapsed
string tsOut = elapsed.ToString(#"m\:ss");
To include the milliseconds, you would write:
string tsOut = elapsed.ToString(#"m\:ss\.ff");
Note, however, that this won't do what you expect if the total timespan is more than 60 minutes. The "minutes" value displayed will be elapsed.Minutes, which is basically the same as ((int)elapsed.TotalMinutes) % 60). So if the total time was 70 minutes, the above will show 10:00.
If you want to show the total minutes and seconds reliably, you have to do the math yourself.
int minutes = (int)elapsed.TotalMinutes;
double fsec = 60 * (elapsed.TotalMinutes - minutes);
int sec = (int)fsec;
int ms = 1000 * (fsec - sec);
string tsOut = String.Format("{0}:{1:D2}.{2}", minutes, sec, ms);

I've coded this way:
using System.Diagnostics;
...
Stopwatch watch = new Stopwatch();
watch.Start();
// here the complex program.
...
watch.Stop();
TimeSpan timeSpan = watch.Elapsed;
Console.WriteLine("Time: {0}h {1}m {2}s {3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);

//try it
Stopwatch sw = new Stopwatch();
sw.Start();
Thread.Sleep(10382);
sw.Stop();
Console.Write(sw.Elapsed.Duration());

Review the documentation for TimeSpan, the struct returned by stopwatch.Elapsed. You want either the Minutes or TotalMinutes property.
If you're measuring a 62 minute span, ts.Minutes will return 2, and ts.TotalMinutes will return 62.

TimeTakenOutput.Text = "0" + myStopWatch.Elapsed.Minutes.ToString()
+ ":" + myStopWatch.Elapsed.Seconds.ToString() + "mins";

ts.Minutes

Related

Sum of multiple TimeSpan

I have to do the sum of more time spans in a DataTable to use the code below, but the total sum is wrong, what is due to this:
DataTable(dt) values:
09:21
08:28
08:46
04:23
Total hours: 30,97 //97 minutes is not correct
C# Code:
TimeSpan totaleOreMarcaTempo = TimeSpan.Zero;
int conta = 0;
foreach (DataRow dr in dt.Rows)
{
String OreMarcaTempo = tm.ConteggioOreGiornaliere(dr["Data"].ToString()); //This string contains at each cycle 09:21 08:28 08:46 04:23
TimeSpan oreMarcatempo = TimeSpan.Parse(OreMarcaTempo.ToString());
totaleOreMarcaTempo = totaleOreMarcaTempo + oreMarcatempo;
conta++;
}
labelTotaleOreMarcaTempoMod.Text = "" + (int)totaleOreMarcaTempo.TotalHours + ":" + totaleOreMarcaTempo.Minutes.ToString(); //30:58
30.97 is the correct number of hours. It does not mean "30 hours and 97 minutes".
30.97 hours is 30 hours and 58 minutes. 58 / 60 is roughly 0.97.
I think you just need to format your string properly. One way to format it is:
#"{(int)yourTimeSpan.TotalHours}:{yourTimeSpan.Minutes}"
Value 30.97 is correct (30.97 hours, where 0.97 is hour (60 minutes * 0.97 = 58 minutes),
you just need convert fraction of TotalHours to minutes.
var raw = "09:21 08:28 08:46 04:23";
var totalTimespan =
raw.Split(" ")
.Select(TimeSpan.Parse)
.Aggregate(TimeSpan.Zero, (total, span) => total += span);
// Use integer value of TotalHours
var hours = (int)totalTimespan.TotalHours;
// Use actual minutes
var minutes = totalTimespan.Minutes
var output = $"{hours}:{minutes}";
var expected = "30:58";
output.Should().Be(expected); // Pass Ok
You have to change the Format. 0,98 hours = 58,2 minutes
labelTotaleOreMarcaTempoMod.Text =string.Format ("{0:00}:{1:00}:{2:00}",
(int)totaleOreMarcaTempo.TotalHours,
totaleOreMarcaTempo.Minutes,
totaleOreMarcaTempo.Seconds);
To print out a TimeSpan "correctly", just use the correct formatting:
labelTotaleOreMarcaTempoMod.Text = totaleOreMarcaTempo.ToString("c");
or
labelTotaleOreMarcaTempoMod.Text = totaleOreMarcaTempo.ToString("hh':'mm");
EDIT Do note (thanks, Basin) that the second form ignores days.
Reference: Standard TimeSpan Format Strings and Custom TimeSpan Format Strings
30.97 is the correct value but not HH:mm format.
For me the correct solution is :
var total = Math.Floor( totaleOreMarcaTempo.TotalMinutes / 60).ToString() + ":" + Math.Floor( totaleOreMarcaTempo.TotalMinutes % 60).ToString();

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();
}

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);

How do you convert Stopwatch ticks to nanoseconds, milliseconds and seconds?

This is a very basic question...quite embarassing, but here goes:
I have a Stopwatch block in C# code. I determine the elapsed time in ticks and then want to convert to ns, ms, s. I know that the Frequency is provided by the Stopwatch class and that it is required for conversion.
Thanks
Stopwatch.Elapsed is a TimeSpan, so you can do myStopwatch.Elapsed.TotalMilliseconds, myStopwatch.Elapsed.TotalSeconds, etc.
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
// Do something
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(1);
}
// Stop timing
stopwatch.Stop();
// Write result
Console.WriteLine("Time elapsed (s): {0}", stopwatch.Elapsed.TotalSeconds);
Console.WriteLine("Time elapsed (ms): {0}", stopwatch.Elapsed.TotalMilliseconds);
Console.WriteLine("Time elapsed (ns): {0}", stopwatch.Elapsed.TotalMilliseconds * 1000000);
Output:
Time elapsed (s): 2.4976622
Time elapsed (ms): 2497.6622
Time elapsed (ns): 2497662200
Note that stopwatch.ElapsedMilliseconds returns a long and is thus only precise up to the millisecond, while stopwatch.Elapsed.TotalMilliseconds returns a double and has the same precision as stopwatch.ElapsedTicks, except it's easier to use. ILSpy shows that TimeSpan.TotalMilliseconds is computed using ticks anyway.
According to MSDN, Frequency tells you the number of ticks per second. Therefore:
Stopwatch sw = new Stopwatch();
// ...
double ticks = sw.ElapsedTicks;
double seconds = ticks / Stopwatch.Frequency;
double milliseconds = (ticks / Stopwatch.Frequency) * 1000;
double nanoseconds = (ticks / Stopwatch.Frequency) * 1000000000;
Stopwatch.Frequency gives you ticks/second.
So, if you have ticks, you can just divide by frequency to get seconds:
long ticks = sw.ElapsedTicks;
double ns = 1000000000.0 * (double)ticks / Stopwatch.Frequency;
double ms = ns / 1000000.0;
double s = ms / 1000;
For example, you can do:
static void Main()
{
Stopwatch sw = new Stopwatch();
sw.Start();
System.Threading.Thread.Sleep(3456);
sw.Stop();
long ticks = sw.ElapsedTicks;
double ns = 1000000000.0 * (double)ticks / Stopwatch.Frequency;
double ms = ns / 1000000.0;
double s = ms / 1000;
Console.WriteLine("{0}, {1}, {2}", ns, ms, s);
Console.ReadKey();
}
Which, on my system, prints:
3455650175.58075, 3455.65017558075, 3.45565017558075
Use this class:
public static class Utility
{
public static long ElapsedNanoSeconds(this Stopwatch watch)
{
return watch.ElapsedTicks * 1000000000 / Stopwatch.Frequency;
}
public static long ElapsedMicroSeconds(this Stopwatch watch)
{
return watch.ElapsedTicks * 1000000 / Stopwatch.Frequency;
}
}
Then you can get the elapsed nanoseconds/microseconds just like this:
var stopwatch = Stopwatch.StartNew();
//... measured code part
Console.WriteLine(stopwatch.ElapsedNanoSeconds());
// OR
Console.WriteLine(stopwatch.ElapsedMicroSeconds());
For milliseconds you can use the ElapsedMilliseconds() method of Stopwatch.
From the MSDN docs:
Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.
long frequency = Stopwatch.Frequency;
Console.WriteLine(" Timer frequency in ticks per second = {0}",
frequency);
long nanosecPerTick = (1000L*1000L*1000L) / frequency;
Console.WriteLine(" Timer is accurate within {0} nanoseconds",
nanosecPerTick);
Use the Elapsed property:
stopwatch.Elapsed.TotalMilliseconds

How do i convert HH:MM:SS into just seconds using C#.net?

Is there a tidy way of doing this rather than doing a split on the colon's and multipling out each section the relevant number to calculate the seconds?
It looks like a timespan. So simple parse the text and get the seconds.
string time = "00:01:05";
double seconds = TimeSpan.Parse(time).TotalSeconds;
You can use the parse method on aTimeSpan.
http://msdn.microsoft.com/en-us/library/system.timespan.parse.aspx
TimeSpan ts = TimeSpan.Parse( "10:20:30" );
double totalSeconds = ts.TotalSeconds;
The TotalSeconds property returns the total seconds if you just want the seconds then use the seconds property
int seconds = ts.Seconds;
Seconds return '30'.
TotalSeconds return 10 * 3600 + 20 * 60 + 30
TimeSpan.Parse() will parse a formatted string.
So
TimeSpan.Parse("03:33:12").TotalSeconds;
This code allows the hours and minutes components to be optional. For example,
"30" -> 24 seconds
"1:30" -> 90 seconds
"1:1:30" -> 3690 seconds
int[] ssmmhh = {0,0,0};
var hhmmss = time.Split(':');
var reversed = hhmmss.Reverse();
int i = 0;
reversed.ToList().ForEach(x=> ssmmhh[i++] = int.Parse(x));
var seconds = (int)(new TimeSpan(ssmmhh[2], ssmmhh[1], ssmmhh[0])).TotalSeconds;
//Added code to handle invalid strings
string time = null; //"";//"1:31:00";
string rv = "0";
TimeSpan result;
if(TimeSpan.TryParse(time, out result))
{
rv = result.TotalSeconds.ToString();
}
retrun rv;

Categories