I have issue that I cant solve. I am trying to add minutes and subtract minutes. basically be in that 30 minutes block range. However, in my code below I am trying to get my key value and add 30 minutes but for some reason AddMinutes gives an error:
Cannot resolve symbol AddMinutes.
here is my code:
var results = JsonConvert.DeserializeObject<dynamic>(barCodeValue);
var gettingTheName = (string) results.Evaluation.Value;
TextHeader.text = gettingTheName;
var qrCodeString = $"https://**************.firebaseio.com/Evaluations/.json?orderBy=\"$key\"&startAt=\"{gettingTheName}\"&limitToFirst=1";
var matchingsLink = new WebClient().DownloadString(qrCodeString);
var objs = JObject.Parse(matchingsLink);
var someId = objs.First.First["Active"].ToString();
var data = objs[gettingTheName];
try
{
if (!((bool)data["Active"] == false && (bool)data["Completed"] &&
DateTime.Now < data["ScheduleStartTime"].AddMinutes(30) &&
DateTime.Now > data["ScheduleStartTime"].AddMinutes(-30)))
You are using AddMinutes() method to the JToken type object. AddMinutes only works with DateTime.
DateTime.Parse("dateInStringFormat") will parse the string to DateTime format.. to which you can then add Minutes to.
DateTime.Now < DateTime.Parse(data["ScheduleStartTime"].ToString()).AddMinutes(30) &&
DateTime.Now > DateTime.Parse(data["ScheduleStartTime"].StoString()).AddMinutes(-30)))
This is probably because data["ScheduleStartTime"] is not an instance of DateTime, since JSON has no built in representation of dates or times. What is most likely is data["ScheduleStartTime"] is an ISO 8601 date represented as a string, in which case you should parse it before comparing it to DateTime.Now:
// ...
var scheduleStartTime = DateTime.Parse(data["ScheduleStartTime"].ToString());
if (!((bool)data["Active"] == false && (bool)data["Completed"] &&
DateTime.Now < scheduleStartTime.AddMinutes(30) &&
DateTime.Now > scheduleStartTime.AddMinutes(-30)))
// ...
Related
I have a database table with columns of type dateTime.
Now I need to see if there already is a row with today's date, but I don't know how to compare the column with the current date without the hour, minutes, seconds.
Basically I have 2022-02-04 14:06:21.080 and I need to check if there is a row created on 2022-02-04.
I'm looking for something like
if (db.dates.Where(x => x.SentDate == Date.Now).Count() > 0)
{
// Do something
}
else
{
// Do something else
}
I only need to see if it has a date from today it doesn't matter what time it was created.
Any help is much appreciated!
If you're filtering for a specific date you can use the DateTime.Date property on both DateTime objects. This will compare the date component of the DateTime:
db.dates.Where(x => x.SentDate.Date == DateTime.Now.Date)
// or
db.dates.Where(x => x.SentDate.Date == DateTime.Today)
If you have a nullable DateTime? column, then you use the Value property along with HasValue:
db.dates.Where(x => x.SentDate.HasValue
&& x.SentDate.Value.Date == DateTime.Today)
Unfortunately, expression trees do not support the null propagation operator ?. so we need to use the above method instead.
DateTime.Date can also be used for date ranges, but take care with the upper bound.
PS: DateTime.Today is the same as DateTime.Now.Date
You can check a date range
var today = DateTime.Today;
var tomorrow = today.AddDays(1);
if(db.dates.Where(x => x.SentDate >= today && x.SentDate < tomorrow) ...
The DateTime.Today Property gets the current date with the time component set to 00:00:00.
You can check a date range
var today = DateTime.Today;
var tomorrow = today.AddDays(1);
if(db.dates.Where(x => x.SentDate >= today && x.SentDate < tomorrow) ...
The DateTime.Today Property gets the current date with the time component set to 00:00:00.
Note that we test the lower bound with >= today (with today meaning today at 00:00:00) but the upper one with < tomorrow, since we do not want to include tomorrow at 00:00:00.
Another way is to convert the dates to string and compare.
if(db.dates.Any(m=>m.SentDate.ToString("d") == DateTime.Now.ToString("d"))){
//Do something else
}
else
{
// Do something else
}
If you use MS SQL Server you can use a special function EF.Functions.DateDiff that was created to be used with EF. It can count datetime difference from seconds to months. DateDiffDay is used to count days.
var dateTimeNow = DateTime.Now;
if (db.dates.Any(x => EF.Functions.DateDiffDay(x.SentDate , dateTimeNow) == 0 )
{
// ... there are today's dates
}
// ...
Is it possible to make a pattern for NodaTime's LocalTime, which matches the ISO 8601 standard for times? That is, can you make (minutes and) seconds optional, like you can make fractional seconds optional? I wish to be able to always have hours and minutes, but add everything else only when needed.
This doesn't exist in NodaTime currently, nor does it exist as an option for the built in DateTime and DateTimeOffset objects.
Probably the best you could do is to create two patterns and add some logic for which to use.
var p1 = LocalTimePattern.ExtendedIsoPattern;
var p2 = LocalTimePattern.CreateWithInvariantCulture("HH:mm");
// formatting
LocalTime t = // your input
var p = t.Second == 0 && t.TickOfSecond == 0 ? p2 : p1;
string s = t.Format(p);
// parsing
string s = // your input
var result = p1.Parse(s);
if (!result.Success)
result = p2.Parse(s);
if (!result.Success)
// throw some exception, etc.
LocalTime t = result.Value;
I am having trouble comparing times.
From what I have researched it most likely is due to the time not having a date.
My code,
This gets a dateTime value from the database.
var getDateTime = sql.Staff_Time_TBLs.Where(p => p.Staff_No ==
SelectedEmployee.Key && p.Date_Data == day).Select(p => p.Time_Data_1).ToList();
DateTime dateTimeGet = Convert.ToDateTime(getDateTime);
dateTimeGet returns a value like this "2012/12/12 15:03:00.000"
I then declare variables to hold the time.
TimeSpan startCompare = TimeSpan.Parse("15:00");
TimeSpan endCompare = TimeSpan.Parse("21:00");
Then comparing the values Compare DateTime
if ((endCompare > dateTimeGet) && (startCompare < dateTimeGet))
{
//match found
}
I am getting a compile error,
operands cannot be given to to type timespan and datetime
How do I compare times in this situation?
Just edit your code like this:
if ((endCompare > dateTimeGet.TimeOfDay) && (startCompare < dateTimeGet.TimeOfDay))
{
//match found
}
You could create DateTime values instead of TimeSpan to compare the value, using the Date of your db time:
DateTime startCompare = dateTimeGet.Date.AddHours(15);
DateTime endCompare = dateTimeGet.Date.AddHours(21);
if ((endCompare > dateTimeGet) && (startCompare < dateTimeGet))
{
// match found
}
In the example you showed, actually would be enough to compare the Hour part of dateTimeGet:
if (dateTimeGet.Hour >= 15 && dateTimeGet.Hour <= 21)
// match found
Actually you are comparing time with date in endCompare > dateTimeGet so you are getting the error
operands cannot be given to to type timespan and datetime
To compare time-span you need to extract the time from date in dateTimeGet by simply using TimeOfDay.
if ((endCompare > dateTimeGet.TimeOfDay) && (startCompare < dateTimeGet.TimeOfDay))
{
//match found
}
This will convert the date into time. For more details about TimeOfDayclick here Hope this works fine for you.
The issue is that, as you rightly say, you are comparing dates to times
A time-span is a measurement of time measured in Hours, where as a date-time is a measurement of time measured in days
so 2012/12/12 15:03:00.000 is approximately 735248.625 days or 17645967 hours
which you are then comparing to a timespan of 15 hours
so you need to either add 735248 days to your time span or drop 735248 days form your Date
both can be easily done
If you call the time TimeOfDay property on the date it will ignore the days and just return 0.625 days as 15 hours
Which means your code would look like this
if ((endCompare > dateTimeGet.TimeOfDay ) && (startCompare < dateTimeGet.TimeOfDay))
OR
If you add the time span to the at midnight date it will create the correct date time for comparation
Which means your code would look like this
if ((dateTimeGet.Date + endCompare > dateTimeGet ) && (dateTimeGet.Date + startCompare < dateTimeGet.TimeOfDay))
I would like to query the db for items with a date greater than or equal to a given date.
The date in the db is a datetime and records time.
If the user enters the search string "1/30/2014", they expect entries that occurred at any time on that date to be returned. However, anything that has a time after 12 am is not returned.
I know I could simply add a day to the search string, but is there a more appropriate way?
if (form["closedend"] != "")
{
DateTime d = DateTime.Parse(form["closedend"]);
traces = traces.Where(s => s.date_Closed >= d);
}
You can use the Date property to truncate the time part:
traces = traces.Where(s => s.date_Closed.Date <= d.Date);
On this way you'd include this day since both DateTimes are midnight.
Update if you use LINQ to Entities DateTime.Date is not supported, you could use this solution: Using DateTime in LINQ to Entities
.Where(s => EntityFunctions.TruncateTime(s.date_Closed) <= EntityFunctions.TruncateTime(d))
You said
with a date greater than or equal to a given date
but in your code you write
s.date_Closed <= d
I think you must change <= by >= to obtain dates greater or equal to d, now you're getting dates less or equal to d.
For this example you don't need neccessary any other dll. You can implement other function, which return bool, f.e:
public bool MyFunction(DateTime s)
{
DateTime d = DateTime.Parse(Your constructor);
return (s.date_Closed >= d);
}
var query = from obj in traces
where MyFunction(obj.date_Closed.Date)
select obj;
or:
var query = traces.Where(p => MyFunction(p.data_Closed.Date));
You can use DbFunctions.TruncateTime(StartDateTime) To remove the time from datetime.
if (form["closedend"] != "")
{
DateTime d = DateTime.Parse(form["closedend"]);
traces = traces.Where(s => DbFunctions.TruncateTime(s.date_Closed) >= DbFunctions.TruncateTime(d));
}
Is there a way to compare two DateTime variables in Linq2Sql but to disregard the Time part.
The app stores items in the DB and adds a published date. I want to keep the exact time but still be able to pull by the date itself.
I want to compare 12/3/89 12:43:34 and 12/3/89 11:22:12 and have it disregard the actual time of day so both of these are considered the same.
I guess I can set all the times of day to 00:00:00 before I compare but I actually do want to know the time of day I just also want to be able to compare by date only.
I found some code that has the same issue and they compare the year, month and day separately. Is there a better way to do this?
try using the Date property on the DateTime Object...
if(dtOne.Date == dtTwo.Date)
....
For a true comparison, you can use:
dateTime1.Date.CompareTo(dateTime2.Date);
This is how I do this in order to work with LINQ.
DateTime date_time_to_compare = DateTime.Now;
//Compare only date parts
context.YourObject.FirstOrDefault(r =>
EntityFunctions.TruncateTime(r.date) == EntityFunctions.TruncateTime(date_to_compare));
If you only use dtOne.Date == dtTwo.Date it wont work with LINQ (Error: The specified type member 'Date' is not supported in LINQ to Entities)
If you're using Entity Framework < v6.0, then use EntityFunctions.TruncateTime
If you're using Entity Framework >= v6.0, then use DbFunctions.TruncateTime
Use either (based on your EF version) around any DateTime class property you want to use inside your Linq query
Example
var list = db.Cars.Where(c=> DbFunctions.TruncateTime(c.CreatedDate)
>= DbFunctions.TruncateTime(DateTime.UtcNow));
DateTime dt1 = DateTime.Now.Date;
DateTime dt2 = Convert.ToDateTime(TextBox4.Text.Trim()).Date;
if (dt1 >= dt2)
{
MessageBox.Show("Valid Date");
}
else
{
MessageBox.Show("Invalid Date... Please Give Correct Date....");
}
DateTime? NextChoiceDate = new DateTime();
DateTIme? NextSwitchDate = new DateTime();
if(NextChoiceDate.Value.Date == NextSwitchDate.Value.Date)
{
Console.WriteLine("Equal");
}
You can use this if you are using nullable DateFields.
DateTime dt1=DateTime.ParseExact(date1,"dd-MM-yyyy",null);
DateTime dt2=DateTime.ParseExact(date2,"dd-MM-yyyy",null);
int cmp=dt1.CompareTo(dt2);
if(cmp>0) {
// date1 is greater means date1 is comes after date2
} else if(cmp<0) {
// date2 is greater means date1 is comes after date1
} else {
// date1 is same as date2
}
DateTime econvertedDate = Convert.ToDateTime(end_date);
DateTime sconvertedDate = Convert.ToDateTime(start_date);
TimeSpan age = econvertedDate.Subtract(sconvertedDate);
Int32 diff = Convert.ToInt32(age.TotalDays);
The diff value represents the number of days for the age. If the value is negative the start date falls after the end date. This is a good check.
In .NET 5:
To compare date without time you must use EF.Functions.DateDiffDay() otherwise you will be comparing in code and this means you are probably pulling way more data from the DB than you need to.
.Where(x => EF.Functions.DateDiffDay(x.ReceiptDate, value) == 0);
You can try
if(dtOne.Year == dtTwo.Year && dtOne.Month == dtTwo.Month && dtOne.Day == dtTwo.Day)
....
In your join or where clause, use the Date property of the column. Behind the scenes, this executes a CONVERT(DATE, <expression>) operation. This should allow you to compare dates without the time.
int o1 = date1.IndexOf("-");
int o2 = date1.IndexOf("-",o1 + 1);
string str11 = date1.Substring(0,o1);
string str12 = date1.Substring(o1 + 1, o2 - o1 - 1);
string str13 = date1.Substring(o2 + 1);
int o21 = date2.IndexOf("-");
int o22 = date2.IndexOf("-", o1 + 1);
string str21 = date2.Substring(0, o1);
string str22 = date2.Substring(o1 + 1, o2 - o1 - 1);
string str23 = date2.Substring(o2 + 1);
if (Convert.ToInt32(str11) > Convert.ToInt32(str21))
{
}
else if (Convert.ToInt32(str12) > Convert.ToInt32(str22))
{
}
else if (Convert.ToInt32(str12) == Convert.ToInt32(str22) && Convert.ToInt32(str13) > Convert.ToInt32(str23))
{
}