Domanda

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.

È stato utile?

Soluzione

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 */ }

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top