DateTime logic in LINQ for SQL Server CE - linq

My object 'Job' has LastTimeFinishedRunning which is DateTime and RunIntervalMinutes which is an int. I need to add them together and compare against current time.
Something like this:
Job jobToRun = ctx.Jobs.Where
(job => DateTime.Now > Job.LastTimeFinishedRunning.Add(TimeSpan.FromMinutes(job.RunIntervalMinutes))).FirstOrDefault();
Well, the .Add() doesn't work of course....
neither works this:
DateTime.Now > EntityFunctions.AddMinutes(job.LastTimeFinishedRunning, job.RunIntervalMinutes)
or this:
DateTime.Now > System.Data.Objects.SqlClient.SqlFunctions.DateAdd("minute", job.RunIntervalMinutes, job.LastTimeFinishedRunning)
...because it's SQL Server CE provider
Any suggestions? Thx.
Update:
I guess my only option here is to store ticks in LastTimeFinishedRunning by switching it from DateTime to long in DB. So the code would look something like this:
long ticks = DateTime.Now.Ticks;
Job jobToRun = ctx.Jobs.Where
(job => ticks > Job.LastTimeFinishedRunning + job.RunIntervalMinutes * 1000 * 10000).FirstOrDefault();

Related

EF Core 5 Sum difference between two date times

We have upgraded to net 5 / ef core 5, and many of our queries have needed "fixing" due to the changes that have been made.
In reality, the queries were horribly inefficient, because the LINQ could not be translated to SQL and now this has been brought to our attention; one solution is to force this to be worked on the client instead of the SQL Server... however I would like this to make this more efficient.
Below is a query that I can't find a way to do efficiently:
DateTime toDate = DateTime.Now.AddDays(NumberofDays + 1).Date;
MyInsights.AvailableHours = DatabaseContext.WorkCenterSchedules
.Where(x => x.ForWorkCenter.WorkCenterId == WorkCenterID && x.dateTo > DateTime.Now && x.dateTo < toDate)
.Sum(y => (y.dateTo - (DateTime.Now > y.dateFrom ? DateTime.Now : y.dateFrom)).TotalMinutes) / 60;
The error is:
This could be changed to the following:
DateTime toDate = DateTime.Now.AddDays(NumberofDays + 1).Date;
List<WorkCenterSchedule> schedules = DatabaseContext.WorkCenterSchedules
.Where(x => x.ForWorkCenter.WorkCenterId == WorkCenterID && x.dateTo > DateTime.Now && x.dateTo < toDate).ToList();
MyInsights.AvailableHours = schedules.Sum(y => (y.dateTo - (DateTime.Now > y.dateFrom ? DateTime.Now : y.dateFrom)).TotalMinutes) / 60;
However, this is far from ideal. I know EF Core isn't ideal for complex queries, but I feel like I am missing something obvious here, is there something I can do to improve this?
You might be able to leverage SQL Server's DATEDIFF function:
EF.Functions.DateDiffMinute(y.dateTo, DateTime.Now > y.dateFrom ? DateTime.Now : y.dateFrom)

Subtract Time from CSV using Ruby

Hi I would like to subtract time from a CSV array using Ruby
time[0] is 12:12:00AM
time[1] is 12:12:01AM
Here is my code
time_converted = DateTime.parse(time)
difference = time_converted[1].to_i - time_converted[0].to_i
p difference
However, I got 0
p time[0].to_i gives me 12
is there a way to fix this?
You can use Time#strptime to define the format of the parsed string.
In your case the string is %I:%M:%S%p.
%I = 12 hour time
%M = minutes
%S = seconds
%p = AM/PM indicator
So to parse your example:
require 'time'
time = %w(12:12:00AM 12:12:01AM)
parsed_time = time.map { |t| Time.strptime(t, '%I:%M:%S%p').to_i }
parsed_time.last - parsed_time.first
=> 1
Use the Ruby DateTime class and parse your dates into objects of that class.

1601/01/01 of lastLogonTimeStamp attribute

I'm using lastLogonTimeStamp to track the users last logon time as the following code:
$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$ADSearch = New-Object System.DirectoryServices.DirectorySearcher
$ADSearch.SearchRoot ="LDAP://$Domain"
$ADSearch.SearchScope = "subtree"
$ADSearch.PageSize = 100
$ADSearch.Filter = "(objectClass=user)"
$properies = #("distinguishedName",
"sAMAccountName",
"mail",
"lastLogonTimeStamp")
foreach ($pro in $properies) {
$ADSearch.PropertiesToLoad.add($pro)
}
$userObjects = $ADSearch.FindAll()
foreach ($user in $userObjects) {
$logon = $user.Properties.Item("lastLogonTimeStamp")[0]
$lastLogon = [datetime]::fromfiletime($logon)
$lastLogon= $lastLogon.ToString("yyyy/MM/dd")
$lastLogon
}
I've gotten so far:
1601/01/01
1601/01/01
3/12/2012
1601/01/01
3/19/2015
This is not the first time I'm bloody confused about the 1601/01/01 value. And I've read also the MS document about this value and for me it's nonsense, it does not describe much what is the purposes of it. Not only lastLogonTimeStamp has this output, many other attributes have return this as well. So my questions are:
What is the purpose of this value?
In this case, what should I return as a proper human readable output ? (This attribute is not valid for this user?)
There is a known bug with the "last logon timestamp" and Windows 2016 domain controllers.
LDAP simple bind are not updating the last logon timestamp like previous OS ( 2012, 2008 ). Be careful.
I spent 2 months with MS on this. A patch will be released eventually... but for now it's not fixed.

In windowsphone converting current time into millisecond

i have a time format like this:
string s = DateTime.Now.ToString();
which gives me output like
11/29/2013 6:26:13PM
Now how can i convert this output into millisecond in windowsPhone???
Updated:
First i want to save the current time when the user launch my app. after that whenever the user launch my app again then i also get the time and compare the current launching time with previously stored time and check whether the time difference becomes "one day" or not.
For this comparison i need to covert 11/29/2013 6:26:13PM this into millisecond.
Another question tell me how can i convert "6:26:13PM" only this into millisecond??
If I understood correctly just do this:
Create a date from your input:
DateTime yourInitialDateTime = DateTime.Parse("11/29/2013 6:26:13PM");
After that
TimeSpan span = DateTime.Now - yourInitialDateTime;
So in span.TotalDays you will have how many days has passed.
Edit
If you have only the time of day and want to know the millisecond of that time you must add a date and subtract it with hour 0:00:00 like this:
string dummyDate = "01/01/0001";
DateTime end = DateTime.Parse(dummyDate + " " + "6:26:13PM");
var milli = end.Subtract(new DateTime()).TotalMilliseconds;
That is it.
Try this.
var ThatDay = DateTime.Now.AddDays(-1); //This is hard coded but you have to get from where you are storing.
var Today = DateTime.Now;
var Diff = (Today - ThatDay).Milliseconds;
var FriendlyDiff = (Today - ThatDay).ToFriendlyDisplay(5);
public static class TimeSpanExtensions
{
private enum TimeSpanElement
{
Millisecond,
Second,
Minute,
Hour,
Day
}
public static string ToFriendlyDisplay(this TimeSpan timeSpan, int maxNrOfElements)
{
maxNrOfElements = Math.Max(Math.Min(maxNrOfElements, 5), 1);
var parts = new[]
{
Tuple.Create(TimeSpanElement.Day, timeSpan.Days),
Tuple.Create(TimeSpanElement.Hour, timeSpan.Hours),
Tuple.Create(TimeSpanElement.Minute, timeSpan.Minutes),
Tuple.Create(TimeSpanElement.Second, timeSpan.Seconds),
Tuple.Create(TimeSpanElement.Millisecond, timeSpan.Milliseconds)
}
.SkipWhile(i => i.Item2 <= 0)
.Take(maxNrOfElements);
return string.Join(", ", parts.Select(p => string.Format("{0} {1}{2}", p.Item2, p.Item1, p.Item2 > 1 ? "s" : string.Empty)));
}
}

ArgumentError invalid date in DateTime#change

When doing
startTime = DateTime.now
startTime = startTime.change(:min => (startTime.min / 5.to_f).ceil * 5)
our production server occasionally produces the following exception
A ArgumentError occurred in controller#action:
invalid date
/opt/ruby-enterprise-1.8.7-2009.10/lib/ruby/1.8/date.rb:1519:in `civil'
vendor/bundle/ruby/1.8/gems/activesupport-3.0.9/lib/active_support/core_ext/date_time/calculations.rb:37:in `change'
And I just can't figure out what causes the problem nor reproduce it in my development environment. Am I doing something wrong, or what is happening here? What I want to do is create a DateTime instance which is rounded up to the closest 5 min from now.
If DateTime.now.min > 55, then you are setting the min value to 60.
If you only need the time part:
startTime = DateTime.now
new_minute = startTime.min / 5.to_f).ceil * 5
new_hour = DateTime.now.hour
if new_minute == 60
new_minute = 0
new_hour = new_hour + 1
end
new_time = startTime.change(:min => new_minute, :hour => new_hour)
if you need more than this, I'd suggest using activesupport. Then you could do
new_time = startTime + (new_minute - min).minutes

Resources