I have a timer that I want to show minutes:seconds:hundreds of seconds.
Since C# timespan doesn't have a method to get hundreds but only milliseconds, I need to somehow format this.
TimeSpan ts = stopWatch.Elapsed;
currentTime = String.Format("{0:00}:{1:00}:{2:00}", ts.Minutes, ts.Seconds, Math.Round(Convert.ToDecimal(ts.Milliseconds),2));
ClockTextBlock.Text = currentTime;
I've tried with Math.Round and nothing happened. The result is still anywhere from 1-3 digit, like this:
01:12:7
01:12:77
01:12:777
I want format to always be like
01:12:07
01:12:77
You need:
String.Format(#"Time : {0:mm\:ss\.ff}", ts)
Where "ts" is your TimeSpan object. You can also always extend this to include hours etc. The fff stuff is the number of significant digits of the second fractions
You can use a custom TimeSpan format string for that (here we're only displaying the first two digits of the milliseconds with ff, which represent the hundredths):
ClockTextBlock.Text = ts.ToString("mm\\:ss\\:ff");
You could set a DateTime type timezone and plus with Timespan span.
You would get a datetime and format it!
DateTime timezone = new DateTime(1, 1, 1);
TimeSpan span = stopWatch.Elapsed;
ClockTextBlock.Text=(timezone + span).ToString("mm:ss:ff");
Just put the format in toString and it simply will show you the desired format :)
Stopwatch s2 = new Stopwatch();
s2.Start();
Console.WriteLine(s2.Elapsed.ToString(#"hh\:mm\:ss"));
Since a millisecond is 1/1000 of a second, all you need to do is divide the milliseconds by 10 to get 100's of a second. If you are concerned about rounding, then just do it manually before the division.
int hundredths = (int)Math.Round((double)ts.Milliseconds / 10);
currentTime = String.Format("{0}:{1}:{2}", ts.Minutes.ToString(D2), ts.Seconds.ToString(D2), hundredths.ToString(D2);
ClockTextBlock.Text = currentTime;
Related
I take two object from database. One is a filename with date init and second one is a DateTime object like 2021-08-08 17:32:07.880.
First, I converted filename to datetime with the code shown here:
var fileDate = DateTime.ParseExact(filename, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
I have to check that the difference between the first date and the second date is 3 hours 15 min or simply 3 hours.
How do I delete seconds and milliseconds of date 2, and compare them?
I'd go similar to MatJ's recommendation:
You've got your file time, and your DB time, which might have seconds and milliseconds on it. If you do the later one minus the earlier one you get a timespan representing the length of time between the datetimes
dBDate - fileDate
Timespans have a TotalMinutes property that is a decimal. A timespan of 5 minutes 45 seconds would have a TotalMinutes of 5.75
So, if we cast that to an int it cuts off the seconds; simples!
var t = (int)((dBDate - fileDate).TotalMinutes);
Now you can compare your t for equality to 180 (3h) or 195 (3h15h
It is very easy to do !
Try following code :
TimeSpan timeSpan = (firstDate - secondDate)
timeSpan.CompareTo(new TimeSpan(3, 15, 0)) // hrs, mins, seconds
This CompareTo method will return 1 if difference between two times is greater than 3 hrs and 15 mins, otherwise, it will return -1
PS:
firstDate and secondDate are in DateTime
I'm trying to subtract my potentially negative timespan values from 24 hours to change them into positive values.
As an example case:
I want to find how much time is there till 8:00 AM.
If it's 16:00 PM now, timespan gives me -8 ish value so I want to substract it from 24 to get 16.
I'm trying this but it's giving me this error
The DateTime represented by the string is not supported in calendar
System.Globalization.GregorianCalendar.
What I tried ;
string startTime = String.Format("{0:t}", "8:00");
TimeSpan timeLeft = Convert.ToDateTime(startTime).Subtract(DateTime.Now);
if (timeLeft.TotalMinutes < 0 )
{
timeLeft = Convert.ToDateTime(String.Format("{0:H}","24:00")).Subtract(Convert.ToDateTime(timeLeft.Negate())) ;
}
How can I achieve subtracting my potentially negative timespans from 24 hours?
You are confusing TimeSpan and DateTime. I guess there is an easier way:
var eightOClock = TimeSpan.FromHours(8);
var now = DateTime.Now;
var till8again = now.TimeOfDay > eightOClock
? TimeSpan.FromHours(32) - now.TimeOfDay
: eightOClock - now.TimeOfDay;
So if TimeOfDay is less than eight hours (it's before 8am), we take the difference to 8am. If it's greater than 8am, we take the difference to 32hours, which is 8am tomorrow.
A DateTime is an absolute date, happening at a certain day, month, year... It must not be used to represent a specific hour.
So your attempt to convert "8:00", or "24:00" in a DateTime will forcibly fail.
For this you must use TimeSpan (or eventually an integer if you always work with hours).
You can use for example
if(DateTime.Now.TimeOfDay > TimeSpan.FromHours(8))
To see if it's more or less than 8:00.
TimeOfDay will return you the amount of time elapsed for today since midnight.
DateTime has also a lot of useful methods to Add or Substract time, see https://msdn.microsoft.com/fr-fr/library/system.datetime(v=vs.110).aspx for details
Use TimeSpan, and if the startDate is less the Now, add a day to it and then make the comparison.
TimeSpan startTime = new TimeSpan(8,0,0);
TimeSpan now = DateTime.Now.TimeOfDay;
startTime = startTime < now ? startTime.Add(TimeSpan.FromDays(1)) : startTime;
TimeSpan diff = startTime - now;
Another point: the error is coming from the fact that 24:00 doesn't represent 12:00 midnight. 0:00 represents midnight, and that will be a valid DateTime.
Trying to parse the following time
string time = "12:25:1197";
TimeSpan t = TimeSpan.ParseExact(time, "HH.mm.ssff", CultureInfo.InvariantCulture);
What is wrong here?
First, you are using . as a separator, but your string uses :.
Second, that is a quite weird representation of seconds (which is a 60 based number) and milliseconds (which is a 100-based one), so you more likely have:
string time = "12:25:11.97" // remember the quotes
Which should be parsed with:
TimeSpan t = TimeSpan.ParseExact(time, "hh':'mm':'ss.ff", CultureInfo.InvariantCulture);
If you indeed have 12:25:1197 then you can use hh':'mm':'ssff, but that's indeed weird
Btw, if that's two digits for what you call ms, then that's hundreths of seconds, not milliseconds (which woulf be three digits)
This works:
TimeSpan t = TimeSpan.ParseExact(time, "hh\\:mm\\:ssff", CultureInfo.InvariantCulture);
Based on: https://msdn.microsoft.com/en-us/library/ee372287.aspx#Other
I am writing a simple class in C# that all it does is print three float variables to a DOS console (hour, minutes, seconds). The output is something like this: Hour = 3, Minutes = 15, Seconds = 0. But I want to know how would I go about in formatting it to show 3:15:00 rather than Hour = 3, Minutes = 15, Seconds = 0
This is the method I created that prints out the info:
/// <summary>
/// Prints the time to the console
/// </summary>
public void PrintTime()
{
Console.WriteLine(pHour.ToString() + ":" + pMinutes.ToString() + ":" + Seconds.ToString());
}
Can someone help me figure out how to format this? I went online and found out about DateTime but it requires the date as well and I don't need to add that for this homework. Many thanks in advance!
You can use the string format that Console.WriteLine provides:
Console.WriteLine("{0}:{1:00}:{2:00}", pHour, pMinutes, Seconds);
A little bit out of context. One more method is to use DateTime class to output the string
DateTime.Now.ToString("yyyy MM dd HH:mm:ss.fff tt", [System.Globalization.CultureInfo]::GetCultureInfo("en-US"));
The advantage of this method is easy insertion of separators in Date. Disadvantage is you cant insert your normal text inside the format string.
You could use a DateTime object to represent your Time and just disregard the Date part. Or you could use a TimeSpan object to accomplish a similar feat.
Or, just disregard both entirely and print out your input values as is:
int hours = 5;
int minutes = 55;
int seconds = 7;
DateTime dt = new DateTime(2014, 1, 1, hours, minutes, seconds);
TimeSpan ts = new TimeSpan(hours, minutes, seconds);
Console.WriteLine("{0:00}:{1:00}:{2:00}", dt.Hour, dt.Minute, dt.Second);
Console.WriteLine("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds); // This is actually not needed for using a TimeSpan, see next line.
Console.WriteLine(ts);
Console.WriteLine("{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
In action
https://dotnetfiddle.net/6lUwnR
Note that weird stuff will happen if you pass in out of range values in some cases, so make sure to validate your input! :)
How do I read a time value and then insert it into a TimeSpan variables?
If I understand you correctly you're trying to get some user input in the form of "08:00" and want to store the time in a timespan variable?
So.. something like this?
string input = "08:00";
DateTime time;
if (!DateTime.TryParse(input, out time))
{
// invalid input
return;
}
TimeSpan timeSpan = new TimeSpan(time.Hour, time.Minute, time.Second);
From MSDN: A TimeSpan object represents a time interval, or duration of time, measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The largest unit of time used to measure duration is a day.
Here's how you can initialize it to CurrentTime (in ticks):
TimeSpan ts = new TimeSpan(DateTime.Now.Ticks);
TimeSpan span = new TimeSpan(days,hours,minutes,seconds,milliseonds);
Or, if you mean DateTime:
DateTime time = new DateTime(year,month,day,minutes,seconds,milliseconds);
Where all of the parameters are ints.
Perhaps using:
var span = new TimeSpan(hours, minutes, seconds);
If you mean adding two timespans together use:
var newSpan = span.Add(new TimeSpan(hours, minutes, seconds));
For more information see msdn.
You can't change the properties of a TimeSpan. You need to create a new instance and pass the new values there.