Function to create 24h periods timestamps? c#
I have database where data is stored along timestamp entries, that are keys.
i need a function that can transform a date like DateTime.Now into a timestamp interval representing, for today as example, Aug 3开发者_如何学C0th 00:00:00h to Aug 30th 23:59:59h.
How could i write that function?
What i want is to do something like
select all from table where timestamp is between a and b.(those and b values would represent the initial and terminal timestamps for a day.)
I did not create the db, i cannot modify it, i can only query it.
This will return a tuple representing the interval you probably want:
Tuple<DateTime,DateTime> GetDateInterval(DateTime datetime) {
var start = datetime.Date;
var end = start.AddDays(1).AddTicks(-1);
return new Tuple<DateTime, DateTime>(start, end);
}
Usage:
var interval = GetDateInterval(DateTime.Now);
Console.WriteLine(interval.Item1);
Console.WriteLine(interval.Item2);
Output:
30.08.2011 0:00:00
30.08.2011 23:59:59
Maybe DateTime.Now.TimeOfDay.Ticks
is what you are looking for.
Hard to tell what you want, but here is a way to get the interval:
var start = DateTime.Today;
var end = start.AddDays(1).AddSeconds(-1);
It's hard to answer how you should store the values in the DB since you haven't provided enough details about the table layout.
If you have the scope of a day, you can calculate the ticks withing the day:
// ----------------------------------------------------------------------
public long GetTicksOfDay( DateTime moment )
{
return moment.Subtract( moment.Date ).Ticks;
} // GetTicksOfDay
I think what you need is a TimeSpan.
You can just substract one DateTime from another, and the result will be a TimeSpan of the difference.
I guess you might try using a structure as a TimeInterval:
public struct TimeInterval
{
private readonly DateTime _startTime;
private readonly DateTime _endTime;
public DateTime StartTime { get { return _startTime; } }
public DateTime EndTime { get { return _endTime; } }
public TimeInterval(DateTime now)
{
_startTime = now.Date;
_endTime = now.Date.AddDays(1).AddTicks(-1);
}
}
You can call it:
TimeInterval day = new TimeInterval(DateTime.Now);
精彩评论