Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在c#中获取下次的日期时间?_C#_Datetime_Caching - Fatal编程技术网

如何在c#中获取下次的日期时间?

如何在c#中获取下次的日期时间?,c#,datetime,caching,C#,Datetime,Caching,我在项目中使用IMemoryCache,我想为缓存项设置一个绝对过期时间。 我想创建一个到期时间,每天为下一个预定义时间(多个时间点)设置到期时间 例如: 过期时间设置为09:00和18:00 如果当前时间为08:00,则过期时间设置为当天09:00 如果当前时间为17:30,则到期时间设置为当天18:00 如果当前时间为21:00,则到期时间设置为第二天09:00 目前,每天只有一个特定的时间将到期日期设置为,我做了类似的事情: if (DateTime.Now.Subtract(DateTi

我在项目中使用IMemoryCache,我想为缓存项设置一个绝对过期时间。 我想创建一个到期时间,每天为下一个预定义时间(多个时间点)设置到期时间

例如: 过期时间设置为09:00和18:00

如果当前时间为08:00,则过期时间设置为当天09:00

如果当前时间为17:30,则到期时间设置为当天18:00

如果当前时间为21:00,则到期时间设置为第二天09:00

目前,每天只有一个特定的时间将到期日期设置为,我做了类似的事情:

if (DateTime.Now.Subtract(DateTime.Today).Hours < expHour)
{
    cacheExpTime= DateTime.Today + expTime;
}
else
{
   cacheExpTime= DateTime.Today.AddDays(1) + expTime;
}
if(DateTime.Now.Subtract(DateTime.Today.Hours)
我会这样做,将所有到期时间放入一个有序的
TimeSpan
枚举表中。请注意,我尚未测试此代码,因此使用此代码的风险自负

我还假设时区不是一个问题,并且枚举将始终至少有一个到期时间

public DateTime GetCacheExpiryDateTime(IOrderedEnumerable expiryTimes)
{
var now=DateTime.now;
var isNextDay=假;
//在列表中查找大于当前时间的第一个到期时间
//如果没有,请将nextespirtime设置为列表中的第一次(第二天)
TimeSpan nextExpiryTime=expiryTimes.FirstOrDefault(time=>now.TimeOfDay
保持简单易读:

public static DateTime GetExpirationDate(DateTime cacheDate)
{
    if (cacheDate.TimeOfDay < TimeSpan.FromHours(9))
        return cacheDate.Date.AddHours(9);
    
    if (cacheDate.TimeOfDay < TimeSpan.FromHours(21))
        return cacheDate.Date.AddHours(21);
    
    return cacheDate.Date.AddDays(1).AddHours(9);
}
publicstaticdatetime GetExpirationDate(DateTime cacheDate)
{
if(cacheDate.TimeOfDay
那么,什么不起作用呢?如果您的过期时间仅为上午9点/晚上9点,这就可以了。也许将来您可能希望将其更改为可通过UI进行配置,以便在缓存过期时进行更改。你的代码必须重写。