开发者

how to get datetime with +- 10 seconds Buffer?

i have:

jobElement.CreationDate = jobElement.CreationDate + TimeSpan.FromHours(24.0);

i would like to have not strictly 24 hours, but w开发者_开发百科ith +- 10 seconds Buffer. like 23.59.10 and 00.00.10

hot to reach that with c#?


This will generate CreationDate + 23:50 and CreationDate + 24:10 with equal probability:

Random random = new Random(); 
TimeSpan buffer = TimeSpan.FromSeconds(10);

TimeSpan span = TimeSpan.FromHours(24.0);

// 50% of the time do this
if(random.Next() % 2 == 0)
{
    span += buffer;
}
// The rest of the time do this
else
{
    span -= buffer;
}

jobElement.CreationDate = jobElement.CreationDate + span;


What do you need to do with that?

If you need to any comparison create custom class with overwritten equality operators.


I'm not 100% sure what you want here but I'll give it a shot

DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(1).AddSeconds(8);

These two are now 24 hours and 8 seconds apart.

Then if you want to see if they are "almost" 24 hour appart, you can do something like this:

if( Math.Abs((dt1-dt2.AddDays(-1))) < 10 ){
  //dt2 is 24 after dt1 +- 10 seconds 
}else{
  //they are not
}


First time (00.00.00) of current date -/+ 10 secs would be:

DateTime dateFrom = jobElement.CreationDate.Date.AddSeconds(-10);
DateTime dateTo = jobElement.CreationDate.Date.AddSeconds(10);

Is that it?


I'll add this variant. It's different from others because it isn't "second based" but "tick" based (the tick is the smallest time that a TimeSpan/DateTime can compute)

const int sec = 10; // +/- seconds of the "buffer"
const int ticksSec = 10000000; // There are 10000000 Ticks in a second

Random r = new Random();
int rng = r.Next(-sec * ticksSec, sec * ticksSec + 1); // r.Next is upper-bound exclusive
var ts = TimeSpan.FromHours(24) + TimeSpan.FromTicks(rng);
jobElement.CreationDate = jobElement.CreationDate + ts;

There are limits in the Random class (it can't generate a long, and generating a "constrained" long (a long with maxValue = x) is non-trivial based only on the Random class, so this will work for up to 3 minutes and something of "buffer" (214 seconds to be more exact).


If you want +/- 10 with all numbers between

Random r = new Random();
int x = r.Next(-10, 11);
var ts =  TimeSpan.FromHours(24).Add(TimeSpan.FromSeconds((double)x));

jobElement.CreationDate = jobElement.CreationDate + ts;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜