计算可配置小时之间的分钟数

时间:2018-12-18 13:29:17

标签: c# datetime timespan

我有一个Journey对象,它有一个DateTime JourneyStartTime { get; set; }和一个DateTime JourneyEndTime { get; set; }。我想计算出旅程在晚上10点至早上6点之间花费的总分钟数(请注意,这是午夜时分)。

我尝试使用TimeSpans指示晚上10点和早上6点,但是我不确定这是否是最好的数据类型。

此逻辑的域基于保险。 X公司希望为在X-Y小时之间行驶的驾驶员评分。这些时间应该是可配置的。这是一个场景:

  

旅程在同一天的下午5点至下午6点之间进行。 X Inurance公司对晚上10点至早上6点之间的旅程感兴趣。在X公司感兴趣的时间段内,这段旅程花了多少分钟?

上面的答案是:0,但是我的代码给出了60分钟(这里是dotnetFiddle)。

这是代码。

代码

using System;

public class Program
{
    public static void Main()
    {
        var shortSameDayJourney = new Journey {
            JourneyId = 1,
            // start of journey - 5pm - start
            JourneyStartTime = new DateTime(2018, 12, 17, 17, 00, 00, DateTimeKind.Utc),
            // end of journey - 6pm - end
            JourneyEndTime = new DateTime(2018, 12, 17, 18, 00, 00, DateTimeKind.Utc)
        };

        var scoreTimePeriod = new InsurerTimePeriodScoreSetting {
            // start of insurer's time period.
            StartOfTimePeriod = DateTime.Now + TimeSpan.FromHours(22),
            // end of insurer's time period.
            EndOfTimePeriod = DateTime.Now + TimeSpan.FromHours(30)     
        };

        var minutesInTimePeriod = getNumberOfMinutesThatJourneyWasInTimePeriod(shortSameDayJourney, scoreTimePeriod);
        Console.WriteLine("Number of minutes the journey was within the time period the insurer had sepcified:");       
        Console.WriteLine(minutesInTimePeriod + " minutes");
    }

    public static double getNumberOfMinutesThatJourneyWasInTimePeriod(
        Journey journey,
        InsurerTimePeriodScoreSetting insurerTimePeriod) {

        var JourneyStart = journey.JourneyStartTime;
        var JourneyEnd = journey.JourneyEndTime;

        var timeSpan = insurerTimePeriod.EndOfTimePeriod - insurerTimePeriod.StartOfTimePeriod;
        var startDif = (JourneyStart - insurerTimePeriod.StartOfTimePeriod);
        var endDif =  (insurerTimePeriod.EndOfTimePeriod - JourneyEnd);

        var time = timeSpan - startDif - endDif;

        return time.TotalMinutes;
    }
}

public class Journey {
    public int JourneyId {get;set;}
    // journey start date and time in UTC, comes form a tracking device on vehicle.
    public DateTime JourneyStartTime {get;set;}
    // journey end date and time in UTC, comes form a tracking device on vehicle.
    public DateTime JourneyEndTime {get;set;}
}

public class InsurerTimePeriodScoreSetting {
    public DateTime StartOfTimePeriod {get;set;}
    public DateTime EndOfTimePeriod {get;set;}
}

1 个答案:

答案 0 :(得分:2)

Timespan仅给出2 is_singular(s1, tol = 1e-05) # FALSE (a good thing?) [1] FALSE converge_ok(s1, tol = 1e-05) # FALSE (a bad thing?) 0.0259109730912352 0.0259109730912352 FALSE is_singular(s2, tol = 1e-05) # FALSE (a good thing?) [1] FALSE alternate optimisations for original model: q1.bobyqa = glmer(obs ~ can_perc + can_n + time * temp + cloud_cover + factor(burnt) + (1|area) + offset(dat$duration), data=dat, family=poisson, na.action = na.fail, glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun = 2e5))) unable to evaluate scaled gradientModel failed to converge: degenerate Hessian with 1 negative eigenvalues alternate optimisations for original model: q1.bobyqa = glmer(obs ~ can_perc + can_n + time * temp + cloud_cover + factor(burnt) + (1|area) + offset(dat$duration), data=dat, family=poisson, na.action = na.fail, glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun = 2e5))) unable to evaluate scaled gradientModel failed to converge: degenerate Hessian with 1 negative eigenvalues q1.neldermead = glmer(obs ~ can_perc + can_n + time * temp + cloud_cover + factor(burnt) + (1|area) + offset(dat$duration), data=dat, family=poisson, na.action = na.fail, glmerControl(optimizer ="Nelder_Mead", optCtrl = list(maxfun = 2e5))) unable to evaluate scaled gradient Hessian is numerically singular: parameters are not uniquely determined all_fit(q1) bobyqa. : unable to evaluate scaled gradientModel failed to converge: degenerate Hessian with 1 negative eigenvalues[OK] Nelder_Mead. : unable to evaluate scaled gradient Hessian is numerically singular: parameters are not uniquely determined[OK] optimx.nlminb : Parameters or bounds appear to have different scalings. This can cause poor performance in optimization. It is important for derivative free methods like BOBYQA, UOBYQA, NEWUOA.convergence code 9999 from optimxParameters or bounds appear to have different scalings. This can cause poor performance in optimization. It is important for derivative free methods like BOBYQA, UOBYQA, NEWUOA.convergence code 9999 from optimx[ERROR] optimx.L-BFGS-B : Parameters or bounds appear to have different scalings. This can cause poor performance in optimization. It is important for derivative free methods like BOBYQA, UOBYQA, NEWUOA.convergence code 9999 from optimxParameters or bounds appear to have different scalings. This can cause poor performance in optimization. It is important for derivative free methods like BOBYQA, UOBYQA, NEWUOA.convergence code 9999 from optimx[ERROR] nloptwrap.NLOPT_LN_NELDERMEAD : [ERROR] nloptwrap.NLOPT_LN_BOBYQA : [ERROR] nmkbw. : [ERROR] $`bobyqa.` Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod'] Family: poisson ( log ) Formula: obs ~ can_perc + can_n + time * temp + cloud_cover + factor(burnt) + (1 | area) + offset(dat$duration) Data: dat AIC BIC logLik deviance df.resid 311.0473 330.3356 -146.5237 293.0473 54 Random effects: Groups Name Std.Dev. area (Intercept) 1.992 Number of obs: 63, groups: area, 8 Fixed Effects: (Intercept) can_perc can_n time temp -67.4998 -1.3180 0.0239 4.8025 1.7793 cloud_cover factor(burnt)unburnt time:temp -0.3813 18.5676 -0.1748 convergence code 0; 2 optimizer warnings; 0 lme4 warnings $Nelder_Mead. Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod'] Family: poisson ( log ) Formula: obs ~ can_perc + can_n + time * temp + cloud_cover + factor(burnt) + (1 | area) + offset(dat$duration) Data: dat AIC BIC logLik deviance df.resid 311.0473 330.3356 -146.5237 293.0473 54 Random effects: Groups Name Std.Dev. area (Intercept) 1.992 Number of obs: 63, groups: area, 8 Fixed Effects: (Intercept) can_perc can_n time temp -67.48057 -1.31791 0.02389 4.80463 1.78012 cloud_cover factor(burnt)unburnt time:temp -0.38118 18.52637 -0.17483 convergence code 0; 2 optimizer warnings; 0 lme4 warnings $optimx.nlminb <std::runtime_error in pwrssUpdate(pp, resp, tol = tolPwrss, GQmat = GQmat, compDev = compDev, grpFac = fac, maxit = maxit, verbose = verbose): (maxstephalfit) PIRLS step-halvings failed to reduce deviance in pwrssUpdate> $`optimx.L-BFGS-B` <std::runtime_error in pwrssUpdate(pp, resp, tol = tolPwrss, GQmat = GQmat, compDev = compDev, grpFac = fac, maxit = maxit, verbose = verbose): (maxstephalfit) PIRLS step-halvings failed to reduce deviance in pwrssUpdate> $nloptwrap.NLOPT_LN_NELDERMEAD <simpleError in pwrssUpdate(pp, resp, tol = tolPwrss, GQmat = GQmat, compDev = compDev, grpFac = fac, maxit = maxit, verbose = verbose): Downdated VtV is not positive definite> $nloptwrap.NLOPT_LN_BOBYQA <simpleError in pwrssUpdate(pp, resp, tol = tolPwrss, GQmat = GQmat, compDev = compDev, grpFac = fac, maxit = maxit, verbose = verbose): Downdated VtV is not positive definite> $nmkbw. <std::runtime_error in pwrssUpdate(pp, resp, tol = tolPwrss, GQmat = GQmat, compDev = compDev, grpFac = fac, maxit = maxit, verbose = verbose): (maxstephalfit) PIRLS step-halvings failed to reduce deviance in pwrssUpdate> 之间的原始时间  所以我必须更改您的alternate optimisations for q2: q2.bobyqa = glmer(obs ~ s.can_perc + s.can_n + s.time * s.temp + s.cloud_cover + factor(burnt) + (1|area) + offset(dat$s.duration), data=dat, family=poisson, na.action = na.fail, glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun = 2e5))) Model is nearly unidentifiable: large eigenvalue ratio - Rescale variables? q2.neldermead = glmer(obs ~ s.can_perc + s.can_n + s.time * s.temp + s.cloud_cover + factor(burnt) + (1|area) + offset(dat$s.duration), data=dat, family=poisson, na.action = na.fail, glmerControl(optimizer ="Nelder_Mead", optCtrl = list(maxfun = 2e5))) unable to evaluate scaled gradientModel failed to converge: degenerate Hessian with 1 negative eigenvalues all_fit(q2) bobyqa. : Model is nearly unidentifiable: large eigenvalue ratio - Rescale variables?[OK] Nelder_Mead. : unable to evaluate scaled gradientModel failed to converge: degenerate Hessian with 1 negative eigenvalues[OK] optimx.nlminb : Model is nearly unidentifiable: large eigenvalue ratio - Rescale variables?[OK] optimx.L-BFGS-B : unable to evaluate scaled gradientModel failed to converge: degenerate Hessian with 1 negative eigenvalues[OK] nloptwrap.NLOPT_LN_NELDERMEAD : [ERROR] nloptwrap.NLOPT_LN_BOBYQA : [ERROR] nmkbw. : [ERROR] $`bobyqa.` Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod'] Family: poisson ( log ) Formula: n_shreiberi ~ s.can_perc + s.can_n + s.time * s.temp + s.cloud_cover + factor(burnt) + (1 | area) + offset(dat$s.duration) Data: dat AIC BIC logLik deviance df.resid 316.8412 336.1294 -149.4206 298.8412 54 Random effects: Groups Name Std.Dev. area (Intercept) 2.523 Number of obs: 63, groups: area, 8 Fixed Effects: (Intercept) s.can_perc s.can_n s.time s.temp -18.19816 -0.22152 0.45839 0.05239 -0.24983 s.cloud_cover factor(burnt)unburnt s.time:s.temp -0.19691 17.92390 -0.13948 convergence code 0; 1 optimizer warnings; 0 lme4 warnings $Nelder_Mead. Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod'] Family: poisson ( log ) Formula: n_shreiberi ~ s.can_perc + s.can_n + s.time * s.temp + s.cloud_cover + factor(burnt) + (1 | area) + offset(dat$s.duration) Data: dat AIC BIC logLik deviance df.resid 316.8408 336.1290 -149.4204 298.8408 54 Random effects: Groups Name Std.Dev. area (Intercept) 2.524 Number of obs: 63, groups: area, 8 Fixed Effects: (Intercept) s.can_perc s.can_n s.time s.temp -19.29632 -0.22153 0.45840 0.05241 -0.24990 s.cloud_cover factor(burnt)unburnt s.time:s.temp -0.19692 19.02091 -0.13949 convergence code 0; 2 optimizer warnings; 0 lme4 warnings $optimx.nlminb Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod'] Family: poisson ( log ) Formula: n_shreiberi ~ s.can_perc + s.can_n + s.time * s.temp + s.cloud_cover + factor(burnt) + (1 | area) + offset(dat$s.duration) Data: dat AIC BIC logLik deviance df.resid 316.8412 336.1294 -149.4206 298.8412 54 Random effects: Groups Name Std.Dev. area (Intercept) 2.523 Number of obs: 63, groups: area, 8 Fixed Effects: (Intercept) s.can_perc s.can_n s.time s.temp -18.23626 -0.22152 0.45839 0.05239 -0.24983 s.cloud_cover factor(burnt)unburnt s.time:s.temp -0.19691 17.96199 -0.13948 convergence code 0; 1 optimizer warnings; 0 lme4 warnings $`optimx.L-BFGS-B` Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod'] Family: poisson ( log ) Formula: n_shreiberi ~ s.can_perc + s.can_n + s.time * s.temp + s.cloud_cover + factor(burnt) + (1 | area) + offset(dat$s.duration) Data: dat AIC BIC logLik deviance df.resid 316.8412 336.1294 -149.4206 298.8412 54 Random effects: Groups Name Std.Dev. area (Intercept) 2.524 Number of obs: 63, groups: area, 8 Fixed Effects: (Intercept) s.can_perc s.can_n s.time s.temp -18.23581 -0.22155 0.45841 0.05242 -0.24997 s.cloud_cover factor(burnt)unburnt s.time:s.temp -0.19694 17.96246 -0.13943 convergence code 0; 2 optimizer warnings; 0 lme4 warnings $nloptwrap.NLOPT_LN_NELDERMEAD <simpleError in pwrssUpdate(pp, resp, tol = tolPwrss, GQmat = GQmat, compDev = compDev, grpFac = fac, maxit = maxit, verbose = verbose): Downdated VtV is not positive definite> $nloptwrap.NLOPT_LN_BOBYQA <simpleError in pwrssUpdate(pp, resp, tol = tolPwrss, GQmat = GQmat, compDev = compDev, grpFac = fac, maxit = maxit, verbose = verbose): Downdated VtV is not positive definite> $nmkbw. <simpleError in pwrssUpdate(pp, resp, tol = tolPwrss, GQmat = GQmat, compDev = compDev, grpFac = fac, maxit = maxit, verbose = verbose): Downdated VtV is not positive definite> 初始化,以便可以在同一天进行比较

DateTime's

Journey相同

   var shortSameDayJourney = new Journey
   {
       JourneyId = 1,
       // start of journey - 5pm - start
       JourneyStartTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 17, 00, 00, DateTimeKind.Utc),
       // end of journey - 6pm - end
       JourneyEndTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 18, 00, 00, DateTimeKind.Utc)
    };  

现在您只需做一个简单的检查-行程时间是否在InsurerTimePeriodScoreSetting之间

 var scoreTimePeriod = new InsurerTimePeriodScoreSetting
 {
     // start of insurer's time period. 18/12 22:00
      StartOfTimePeriod = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 22, 0, 0, DateTimeKind.Utc),   // DateTime.Now + TimeSpan.FromHours(22),
     // end of insurer's time period. 19/12 6:00
     EndOfTimePeriod = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 6, 0, 0, DateTimeKind.Utc)  // DateTime.Now + TimeSpan.FromHours(30)
 };