I want to make an app that adds 1 minutes and 25 seconds to a TimeLeft variable.
Problem is I have no idea what type of variable this should be, or even how to add 1 minutes 25 seconds to the available time left.
Any guidance would be much appreciated. I'm good with C#, but since I've never done something like, I'm in the dark.
I would suggest you use a DateTime variable. This will let you manipulate the time. If you want to add 1m 25s to a varible, you could simply use:
DateTime newTime = DateTime.Now.AddSeconds(85);
That will add 85 seconds onto the current time (or, in your case, TimeLeft as long as the TimeLeft variable is also a DateTime type)
TimeSpan works well. It's specifically designed to hold a duration of time.
Use the DateTime type. Assuming your TimeLeft variable is an integer, you probably need to convert it to DateTime type first and then perform the add. More information here
Related
I am trying to show the timestamp of when a process begins and when it completes, but my time never increments (even though time in reality does)
DateTime now = DateTime.Now;
txt1.AppendText(now + Environment.NewLine);
//Lengthy process that usually takes 2 - 3 minutes
txt1.AppendText(now);
You are literally using the same variable with the same value as when you first displayed it. You would need to get the time again like this...
DateTime now = DateTime.Now;
txt1.AppendText(now + Environment.NewLine);
//Lengthy process that usually takes 2 - 3 minutes
DateTime timeHasPassed = DateTime.Now;
txt1.AppendText(timeHasPassed);
DateTime is a ValueType. When you assign it to a variable, you are making a copy of the value, not the reference.
This means that when you use DateTime.Now, you have to invoke it via the Get Property to get the latest time value.
txt1.AppendText(DateTime.Now + Environment.NewLine);
//Lengthy process that usually takes 2 - 3 minutes
txt1.AppendText(DateTime.Now);
That's because you captured and stored the DateTime.Now in a variable so it shows the stored value. Use DateTime.Now again instead of using now variable.
Don't use DateTime to measure your process time of your code.
You should never do any increment or math with DateTime.Now because it may be ambiguous due to DST and TimeZone issues.
Use StopWatch to measure elapsed time instead. This class offers high-precision timing in .NET. It is capable of measuring time with sensitivity of around 100s of nanoseconds.
You can use it's Start and Stop methods to control of a StopWatch object.
I have a timespan object that needs to hold only time, without date. I would use
DateTime.Now.TimeOfDay
but the problem is it gives time in the format
15:51:51.7368329
I don't want the milliseconds component. How can I trim it out?
You can either use DateTime.Now.Hour/Minute/Second properties or you could use DateTime.Now.ToString("HH:mm:ss").
Refer here for more info: http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
I believe this is what you may be after:
TimeSpan timeNow = DateTime.Now.TimeOfDay;
TimeSpan trimmedTimeNow = new TimeSpan(timeNow.Hours, timeNow.Minutes, timeNow.Seconds);
Simply subtract away the millisecond part:
DateTime myTime = DateTime.Now.TimeOfDay;
myTime = myTime.AddMilliseconds(-myTime.Millisecond);
It could be done in less code, without first assigning to myTime:
DateTime myTime = DateTime.Now.TimeOfDay.AddMilliseconds(
-DateTime.Now.TimeOfDay.Millisecond);
Although somewhat elegant, it is a bad idea. When accessing TimeOfDay twice, there is a chance that it at some point will have passed another millisecond before the second access. In that case the result would not be zero milliseconds.
If the problem is displaying it, you can do this:
DateTime.Now.ToString("HH:mm:ss")
When displaying to user you can specify needed format. Here is a good tutorial:
http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
You can create new DateTime object passing to constructor only hour, minute, second (it's for saving.)
You can use this function to check what format suits you:
DateTime.Now.GetDateTimeFormats();
This will give you all the Formats like:
"14/05/2011"
"14/05/11"
"14.05.11"
"14-05-11"
"2011-05-14"
etc.
You can do this-
DateTime.Parse(
DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"),
System.Globalization.CultureInfo.CurrentCulture
);
Worked for me :).
I'd like to define a time of day, without necessarily specifying a year, month, day, which would require DateTime.
After I define this Time, I'd like to use all of the nice things about DateTime, i.e. AddMinutes, AddHours, .Hour, .Second, etc.
I guess what I really want the "Time" out of "DateTime", but I can't seem to find it anywhere.
Many thanks in advance!
EDIT:
This is what I was looking for:
// Specify a time of day.
TimeSpan timeSinceMidnight= new TimeSpan(16,00,00); // 4pm
... other code to calculate correct date ...
// Work out scheduled time of day.
DateTime date = new DateTime(2010,12,10).Add(timeSinceMidnight);
Why not just use the standard .NET DateTime class and ignore the date part? It seems that DateTime.ToShortTimeString() could help, or perhaps DateTime.TimeOfDay, which returns a TimeSpan representing the length of time since midnight.
Any other solution would be reinventing the wheel.
Take a look at the TimeSpan structure
Lets say you have a datetime stored somewhere such as a database or you stored it in a variable manually. To strip out the time you can use this.
string.Format("{0:MM/dd/yy}");
edit: oops you meant keep the time not the date.
What is a good data-type for saving hours in .net?
Is it better to use the decimal type or is the double data-type more appropriate. With hours I mean values such as:
2 for two hours
1.5 for 90 minutes
8.25 for 8 hours and 15 minutes.
A good way to represent a number of hours is to use a TimeSpan:
TimeSpan hours = TimeSpan.FromHours(2);
Given the choice between decimal or double I'd probably go for double as there is typically no expectation that the amount of time is represented exactly. If you need an exact decimal representation of your fractional number of hours (which seems unlikely) then use decimal.
You could also consider storing it as an integer in for example seconds, milliseconds or ticks.
The best datatype to store hours is the one designed for it - TimeSpan.
It has methods that allow you to add/subtract/convert it.
As for storage in a database, it really depends on what you are using this for and what kind of resolution is required.
I would use the time datatype - as it will hold the range:
00:00:00.0000000 through 23:59:59.9999999
However, if you need to hold more than 24 hours in this field, you may want to consider a tinyint or int holding the number of minutes (assuming that is the maximum time resolution you require).
In SQL Server use INT or DECIMAL. TIME isn't really ideal for storing a duration because TIME defines a point in time within the 24 hour clock whereas duration is simply an integer or decimal value. You cannot do addition or subtraction with TIME values and there is no obvious way to use TIME to store durations greater than 24hrs.
Why don't use TIME?
You can use DATEADD with TIME to manipulate it easier:
SELECT DATEADD(minute, 30, CAST('2:00:00' AS TIME))
becomes 02:30:00.0000000. And so on..
using the following:-
TimeSpan diff = dt2.TimeOfDay - dt1.TimeOfDay;
d1, d2 are 2 variables of type DateTime and they have got values in them
Now I want to check if there's a difference of 12 hours b/w them
if(diff>12)
{
//do stuff
}
now of course it wont wont coz 12 is an int..so how do I check if the time is more than 12 hrs or not ?? need help with this if statement only..thnx
The general solution is to construct a TimeSpan object that corresponds to the cut-off:
if(diff > TimeSpan.FromHours(12))
{
...
}
If the cut-off corresponds to a multiple of a 'nice' unit of time like days, hours, minutes, seconds or milliseconds as in your example, you could use the TotalXXX property of TimeSpan, as others have posted:
if(diff.TotalHours > 12)
{
...
}
To plainly answer your question, you use one of the properties on the TimeSpan struct, typically the TotalHours property. There are other, simpler, answers here that tells you how to do that, so I won't repeat it.
However, this means I must trust your question to be complete, and I think that just ignoring the date portion will give you edge-cases that you at least need to know about.
For instance, with the following two time-of-day values, how much time is between them?
18:00
08:00
Is it -10 hours, or 14hours between these two?
To properly answer your question, personally I would want you to tell me how you intend to use these values, what it means to you, and give a few examples.
use
if( diff.TotalHours > 12){
....
}
Have you actually used intellisense and noticed the Hours and TotalHours properties on the diff TimeSpan object?
TimeSpan.FromHours you need to use to find the difference
TimeSpan diff = dt2.Substract(dt1);
if (diff.TotalHours > 12)
{
// Do something
}