StartCopying = DateTime.Now;
File.Copy(#"C:\Users\sshap5x\Desktop\line4\shiraDebbi\Hackers.avi", #"C:\Users\sshap5x\Desktop\test\Hackers.avi", true);
EndCopying = DateTime.Now;
CopyingTime1 = (endCopying - startCopying).Duration;
What is the problem with my code?
Copying time is TimeSpan object.
The assignments are to StartCopying and EndCopying but your read the data from other variables startCopying and endCopying.
C# is case sensitive.
And also Duration is a method. so you need to use .Duration()
And as suggested in the comments to your question, for better resolution use the Stopwatch class.
// This prints 0.1 (roughly)
DateTime start = DateTime.Now;
Thread.Sleep(100);
var diff = DateTime.Now - start;
Console.WriteLine(diff.TotalSeconds);
In your code (which wouldn't even compile) you use .Duration as a property when it is in fact a method. In any case, you don't need to call Duration at all because the result returned by the subtraction is a TimeSpan containing the difference. You can then get this diff in whatever format you need (milliseconds, seconds, hours, days, etc.).
The only need for the Duration method is if you are unsure whether the result is negative or positive.
Did you forget the () for Duration and capitalisation for the variables EndCopying and StartCopying?
DateTime StartCopying = DateTime.Now;
DateTime EndCopying = DateTime.Now;
TimeSpan CopyingTime1 = (EndCopying - StartCopying).Duration();
Related
If I have a DateTime variable that's set to the future, and I don't know if it's set to Utc or Local time, how can I find the number of minutes until this time? Something like this:
DateTime futureTime;
// futureTime is set to some value...
int minutesUntilFutureTime = futureTime - DateTime.Now;
You want a TimeSpan object
TimeSpan untilFutureTime = futureTime - DateTime.Now;
TimeSpan has a property called minutes and total minutes, total minutes is what you want.
int minutesUntilFutureTime = untilFutureTime.TotalMinutes;
doc https://learn.microsoft.com/en-us/dotnet/api/system.timespan?view=netframework-4.8
DateTime has a Kind property that allows you to determine whether or not the time is Local or UTC.
It also can be Unspecified in which case I think you just have to guess because you don't have enough information.
Another option could be to use the .ToLocalTime() method to force your DateTime to always be expressed a Local DateTime.
DateTime futureTime;
double minutesUntilFutureTime = (futureTime.ToLocalTime() - DateTime.Now).TotalMinutes;
This is may be silly question. But I am missing logic here. I have to compare dates with date time with hours and minutes (not with seconds).
IF first field time is older then second field execute condition
right now I am doing if (Convert.ToDateTime(newItem["Modified"]) < Convert.ToDateTime(properties.ListItem["Modified"]))
example if("02/12/2015 11:58" < "02/12/2015 12:01") then execute condition.
You could create new DateTime objects with mostly the same values, but with seconds set to 0. Example:
DateTime date1WithoutSeconds = new DateTime(dt1.Year, dt1.Month, dt1.Day, dt1.Hour, dt1.Minute, 0);
DateTime date2WithoutSeconds = new DateTime(dt2.Year, dt2.Month, dt2.Day, dt2.Hour, dt2.Minute, 0);
bool b = date1WithoutSeconds < date2WithoutSeconds;
You could subtract the two dates, and if the TotalSeconds of the difference is less than 60 AND the minues are the same, then they are equal:
var first = Convert.ToDateTime(newItem["Modified"]);
var second = Convert.ToDateTime(properties.ListItem["Modified"]);
if (first.Subtract(second).TotalSeconds < 60 && first.Minute == second.Minute)
{
Console.WriteLine("They are equal");
}
You should use the DateTime.CompareTo method.
Grab and assign both dates as DateTime objects:
DateTime date = Convert.ToDateTime(newItem["Modified"]);
DateTime compareDate = Convert.ToDateTime(properties.ListItem["Modified"]);
You can now use the CompareTo method of the DateTime object to see if the instance is earlier, the same, or later than the other, returning -1, 0, and 1 respectively.
So, following your example: if("02/12/2015 11:58" < "02/12/2015 12:01"), first date being date and second being compareDate, the code:
date.CompareTo(compareDate);
will return -1, telling you the instance invoking the method is earlier than the object you are comparing it to.
Here is the MSDN.
One more way that should work.
DateTime date1 = Convert.ToDateTime(newItem["Modified"]);
DateTime date2 = Convert.ToDateTime(properties.ListItem["Modified"]));
if( date1.AddSeconds(-date1.Second) < date2.AddSeconds(-date2.Second) ) {
}
But, I would wonder...is it really that you need to ignore the seconds and "floor" the result so that 12:59:00 is the same as 12:59:59 but different than 12:58:59 even though there's only a second of difference...or do you need to know that it's greater than a minute of difference? If you really just want to make sure that it is a minute apart, use TimeSpan (date1 - date2).TotalSeconds > 60
I doubt this is likely, but if your DateTime is a string WITH milliseconds, then do:
if( date1.AddSeconds(-date1.Second).AddMilliseconds(-date1.Millisecond) <
date2.AddSeconds(-date2.Second).AddMilliseconds(-date2.Millisecond) )
{
}
First of all, the sample data you've mentioned in your question doesn't include seconds, so by default Convert.ToDateTime will assign '00' as seconds, so it would compare without the seconds.
But let's say that you do provide seconds in the actual data. You can use the following:
var date1 = Convert.ToDateTime(newItem["Modified"]);
var date2 = Convert.ToDateTime(properties.ListItem["Modified"]);
if (date1.AddSeconds(-date1.Second) < date2.AddSeconds(-date2.Second))
The main logic of a utility tool is in a function like this:
private void Run()
{
DateTime startTime = DateTime.Now;
Prepare();
Search();
Process();
DateTime endTime = DateTime.Now;
TimeSpan duration = endTime.Subtract(startTime);
Console.WriteLine("Run took {0:00}:{1:00}:{2:00}",
(int)duration.TotalHours, duration.Minutes, duration.Seconds);
}
When I run this I can see with my own eyes it is taking at least 5 seconds (Process() method spews console output which I can observe happening for 5-6s). But it reports "Run took 00:00:01".
I don't expect time to have microsecond precision but why is it so totally inaccurate here?
Update:
Following advice I also ran a StopWatch over the same period and compared against subtracting two DateTime, and also debugged the code. The two methods agree to a fraction of a second... StopWatch in the debugger had 1139 milliseconds. My hypothesis is that somehow time writing to the console is not included but I have no way to back that up (or disprove it).
I doubt that the problem is with DateTime. Likely, the program finished and sent the output to the console buffer, which is taking its sweet time actually displaying it. What you're seeing is output lag.
To become confident in what you see is what really happens, write for test sake:
DateTime startTime = DateTime.Now;
Thread.Sleep(5000);
DateTime endTime = DateTime.Now;
TimeSpan duration = endTime.Subtract(startTime);
Console.WriteLine("Run took {0:00}:{1:00}:{2:00}",
(int)duration.TotalHours, duration.Minutes, duration.Seconds);
Also, it's better to use Stopwatch class for your purposes
Why not use Stopwatch?
Stopwatch ss = new Stopwatch();
ss.Start();
// Some quantity of work.....
ss.Stop();
Console.WriteLine("Elapsed time: {0}", ss.Elapsed.TotalMilliseconds);
DateTime isn't very accurate for this kind of measurement. You should use the stopwatch class.
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
DateTime startTime = DateTime.Now;
Thread.Sleep(5000);
DateTime endTime = DateTime.Now;
TimeSpan duration = endTime.Subtract(startTime);
Console.WriteLine(duration.Seconds);
Prints "5". Are you sure your test case is what it is?
I have a theory why the following code is not producing the results I need:
endDate = DateTime.UtcNow.AddDays(1).ToShortDateString() + " " +
DateTime.UtcNow.TimeOfDay.Subtract(
new TimeSpan(0, 0, 0, 0, DateTime.UtcNow.TimeOfDay.Milliseconds));
The processor must calculate the DateTime.UtcNow.TimeOfDay.Milliseconds, and due to the time length of a single tick of the CPU (and the time to process this property and return a result), It does not denote that DateTime.UtcNow.TimeOfDay.Milliseconds will subtract the exact amount of milliseconds specified by the DateTime.UtcNow.TimeOfDay
I need to know, what is the simplest and most effective method to remove the amount of milliseconds from DateTime.UtcNow.TimeOfDay, without having to use a huge amount of processor time? This application of mine is pretty big, and this problem is pretty simple. But when this application gets deployed, there are no room for it to be unstable. This milliseconds must be trimmed because it is sent to a stored procedure in SQL Server, and this specific stored procedure does not support milliseconds on DateTimes. I also run into this problem commonly, but I normally convert the date to string (which is a cast on its own), split the string at the full stop at milliseconds, and use the index position 0 to get the time i need. Is there a shorter, more effective way?
Stability and speed is most important to me.
Thanks in advance
Don't repeatedly use the Now/UtcNow property in the same expression. Get the value once, and use the same value in the different places:
DateTime now = DateTime.Now;
endDate = now.AddDays(1).ToShortDateString() + " " +
now.TimeOfDay.Subtract(
new TimeSpan(0, 0, 0, 0, now.TimeOfDay.Milliseconds));
If you only want the date formatted in a special way, and don't need the actual DateTime value, you can just skip the milliseconds in the format, for example:
endDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
As you are sending the value to the database, you should not send it as a string, but as a DateTime value:
DateTime now = DateTime.Now;
DateTime endDate = now - new TimeSpan(0, 0, 0, 0, now.TimeOfDay.Milliseconds);
Everything you need to know about customising the DateTime ToString format is here on MSDN.
In simple terms, something like this:
endDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd hh:mm:ss");
(alter the format as desired)
If you want to remove milliseconds without having any problem on ticks.
DateTime d = DateTime.Now;
var newDate = new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second);
Basically, you create a new DateTime instance from an existing one, but set everything "smaller" then Milliseconds to zero. You can use an extensions method:
public static class DateTimeExtensions
{
public static DateTime ZeroMilliseconds(this DateTime dt)
{
return new DateTime(((dt.Ticks / 10000000) * 10000000), dt.Kind);
}
}
Or for a full example using your code:
var now = DateTime.Now;
endDate = now.AddDays(1).ToShortDateString() + " " + now.ZeroMilliseconds().TimeOfDay;
Use C# DateTime formatting as described very well in the MSDN. Your analysis on milisecond calculation is quite possibly wrong. Also for string concatenation use a StringBuilder
I was just wondering if there is a way to get the current time and set it into a value.
If its 12:06 AM.. I want to get that time and set it into currentTime.
Example
float currentTime = 0;
currentTime = 12.06;
As others have mentioned, the DateTime class would be ideal for this, and to work out the difference between 2 date/times:
DateTime end = DateTime.Now;
DateTime start = new DateTime(2011, 12, 5, 12, 6,0);
double hours = (end - start).TotalHours;
The subtraction of DateTime objects results in a TimeSpan object that you can use to see the hours/minutes etc.
try DateTime class
DateTime dt = DateTime.Now;
Is this what you're looking for?
DateTime currentTime;
currentTime = DateTime.Now;
Don't use floats or strings. You can do all kinds of cool things using DateTime.
Here's how you'd get the hours that someone worked:
var clockIn = new DateTime(2011,12,4,9,0,0); // December 4th, 9 AM
var clockOut = new DateTime(2011,12,4,17,0,0); // December 4th, 5 PM
var duration = clockOut - clockIn; // TimeSpan
Console.Write(duration.TotalHours); // 8
A few people have mentioned how, but as a 'better' recommendation you should use
DateTime currentTime = DateTime.UtcNow
Otherwise you have issues when the clocks go back, if your timing code is run on those days. (plus it is far easier to alter the UTC time to local time than it is to convert a '1am' to UTC (as there will be two of them when the clocks go back)
Well if you really what it as a float then try:
var currentDate = DateTime.Now;
float currentTime = float.Parse((currentDate.Hour > 12 ? currentDate.Hour -12 :
currentDate.Hour) + "." + currentDate.Minute);
I wouldn't recommend comparing dates or time with floats. A better options would be to use timespans.
You should be using a Timespan instance for time related values, you can use the flexibility to get the required values like
TimeSpan ts = DateTime.Now.TimeOfDay;
ts.ToString("hh:mm") // this could be what you are looking for
You could then use ts.TotalHours which would give you fractional hours (as a double) else you could construct a string specifically using ts.Hours ..ts.Minutes play around and it could be prove useful.
Try the following:
DateTime StartTime=StartTime value;
DateTime CurrentTime=DateTime.Now;
TimeSpan dt = CurrentTime.Subtract(StartTime);
In dt you will get a working time period.
If you want to have the difference between two times, then do this:
DateTime dateOne = DateTime.Parse(enteredTime);
DateTime dateTwo = DateTime.Now;
TimeSpan difference = dateOne - dateTwo;