简体   繁体   中英

Calculate difference between DateTime.Now and time(7) value in C#?

I've got a db that contains the schedule for employees reflecting when they should clock in and out. When they punch in, for example, I want to compare the current time with what they're scheduled for. For the life of me I can't seem to work it out. I'm retrieving the scheduled time as so:

if (day=="Friday")
{
    var auth = from d in dc.Dailies
               where d.Number == employee
               select d.FridayStart; ;

}

Which seems fine but none of the examples I'm trying work... one possible problem seems that although I'm storing the scheduled times as time(7) , the query appears to return them as TimeSpan values, which puzzles me.

Well, from your code, you could do

if (day=="Friday")
{
    //auth is expected to be an IQueryable, which derives from IEnumerable, 
    //so it could be many results
    var auth = from d in dc.Dailies
               where d.Number == employee
               select d.FridayStart;

    //So, if you're expecting only one result, and guarantee that will be one,
    //you can use .First() or .Single()
    var timeDifference = auth.First() - DateTime.Now.TimeOfDay;    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM