grails ORM , how to search Date without time - grails

I am using postrges db.
My domain has a date field:
java.util.Date requestedDate;
I am trying to search by date in my controller:
eq ("requestedDate", requestedDate)
This works fine, but the problem is that date and time has to be exactly matching for this. But in application the user will only enter the date to search items (like give me all requests which are made on 2014-02-05 and the browser application will add the current time to the request). So the comparison fails because the user entered time is different from the time during creation of the request.
I tried 'like' but it throws error.
How to compare only date part ?

You could do something like this:
Date now = new Date()
now.clearTime()
def results = Meeting.withCriteria {
between('date', now, now+1)
}
So this strips off the time portion of the current date, and then does a 'between' query (between midnight just gone and midnight 24 hours later).

Still it looks like there is no convenient way to realize this.
You need a small detour by computing the start of the day and the end of the day and use the between operator.
EDIT
I just saw now rcgeorge23 gave you the right example for doing this.

Related

I need to define a custom work week in MS access

I am trying to create a custom function on a form to define a week Number.
I have created a table that defines the week number.
Example WeekNo, StartDay, End Day
example: WeekNo 1 StartDay = 3/29/2020, End Day 4/4/2020
I have a Date box on my form if I enter a date of 3/29/2020
I would like 1 to be populated in my week number box.
On my form in the row source I have designed a Dlookup query
=DLookup("[WeekNumber]", "tblWeekNumber", "[Startdate] >= " & frmSearchNew.dt_Date & "") & [EndDate] <= frmSearchNew.dtDate
When I change to from view I get the error the record source specified on this form does not exist.
The table tblWeekNumber has the fields ID, WeekNo, StartDay and EndDay.
Where am I going wrong? any help is appreciated.
There are quite a few issues with the DLookup that you have put together.
Firstly, the field that you are looking for and the fields that you are using as criteria do not appear to match those in the table - WeekNumber/WeekNo, StartDate/StartDay, EndDate/EndDay;
Next, the logic for the lookup is wrong. You are trying to find a the week number that has a start date that is greater than the entered date, and an end date that is less than the entered date. What you should be looking for is a start date before the entered date, and an end date after the entered date.
Finally, dates are a bit funny in Access. You need to wrap them in '#' so that Access knows they are dates, and you should also take care to disambiguate them - 03/04/2020 could be either 3rd April or 4th March depending on you nationality.
Putting it all together, the final control source should look like:
=DLookUp("WeekNo","tblWeekNumber","StartDay<=#" & Format([dt_Date],"dd-mmm-yyyy") & "# AND EndDay>=#" & Format([dt_Date],"dd-mmm-yy") & "#")
Regards,

Rails - Check if a date belongs to a certain month in where query

Using Rails 6.
I have an ElectricityUsage model, with a Date field, date. I want to extract all the values for amount only for the current month. How would I accomplish this?
What I immediately attempted was the following:
ElectricityUsage.where(habitat: current_user.reservations[0].room.habitat).where(date.month: Date.today.month)
But that obviously doesn't work, and it wouldn't even account for the year, either. My DB is running on PostgreSQL, if that makes a difference.
You can use where with Date.current.all_month, which basically is just translated into a query using BETWEEN where the start date is the first day of the month and end date is the last one:
ElectricityUsage.where(habitat: current_user.reservations[0].room.habitat, date: Date.current.all_month)
This should work for you
ElectricityUsage.where(habitat: current_user.reservations[0].room.habitat).where("EXTRACT(MONTH FROM date) = ?", Date.current.month)
PostgreSQL Date/Time Functions and Operators
Might be a delayed response but you can use date_queries gem
model ElectricityUsage < ActiveRecord::Base
date_queries_for :date
end
Then you can simply use ElectricityUsage.dates_in_this_month to find all the records that false in current month

Timezone independent due date comparison in rails scope

Consider the following case. I have a Voucher model with a datetime activation_due_date field and user model that has up-to-date information about his location (timezone, UTC offset).
I want to check if he requests voucher activation before due date in any of available time zones. For instance, If a due date is set to 28.08.2018 23:59 UTC
I want my scope before_activation_due to check if he requests something before 28.08.2018 - 23:59 in his current time zone so my due date is not something fixed - it depends on users location - In one place it can be after due date and in the other before.
I have tried the following approach.
models/voucher.rb
scope :before_activation_due, lambda { |user|
where('activation_due_date > ? ', Time.current.to_utc + user.utc_offset)
}
My questions are:

Is this a right approach? If not, what is the proper way for dealing with such cases?
How to test such a scope? The current timestamp is probably taken from a database server when comparing datetimes during query execution so I am not sure how to mock it in my specs.
Thanks in advance.
You can store just the timezone of the user, not the offset, then do:
where('activation_due_date > ? ', Time.now.utc.in_time_zone(user.timezone))
where timezone is any valid timezone shown in
rake time:zones
That'd be the more rails-y way to do things at least. But I don't think storing an offset then manually adding it to the time is a bad approach.
To test this, you can manually insert any date you want in to your database. Then you can use a gem like https://github.com/travisjeffery/timecop to travel in time to that point, and test your scope:
Voucher.create(activation_due_date: '2018-01-02 00:00:00')
format = '%Y-%m-%d %H:%M:%S %Z'
time = DateTime.strptime("2018-01-02 00:00:00 Central Time (US & Canada)",format)
Timecop.travel(time)
Voucher.before_activation_due.all ...
One approach is to convert the activation_due_date into the timezone of the user. As you say "my due date is not something fixed - it depends on users location".
To do this as a scope the easiest thing would be to use your databases timezone functions. This depends on which database you are using, but in PostgreSQL it will be something like:-
where('activation_due_date AT TIME ZONE ? > NOW() ', user.timezone)
An even simpler way would be to do a string comparison
where('to_char(activation_due_date, 'YYYYMMDDHH24MISS') > ?', Time.current.in_time_zone(user.timezone).strftime('%Y%m%d%H%M%S');
In this case we are saying what is the time on the wall for the user, and is it less than time in the database (which is "stored" in UTC).

Getting a different result from query with active records

I have tables with UTC dates. When trying to get the day of week by using dow in PostgreSQL, I get the wrong day if the hours flow to the next day (and I need the right dow).
I created a fiddle to show the problem:
http://sqlfiddle.com/#!15/9aa9e/11
If I run the queries locally on my pgAdmin, it will return the correct dow. But on fiddle and from rails, I get the wrong dow. Any ideas?
Ok, so I understood that pgAdmin does it's own dow magic based on my timezone, and when rails sends that, it obviously doesn't happen.
The system I work on relies on the fact that rails does it's conversion magic for UTC datetimes back and forth, which work great if you don't use local postgreSQL timezone related functions such as DOW. What I did not is that it worked fine if I gave the dow the right offset. So here's my solution to the problem if anyone else needs it:
utc_diff = Time.current.time_zone.utc_offset/60/60
# making sure the diff is either + or - (minus is automatic)
utc_diff = utc_diff < 0 ? utc_diff : "+#{utc_diff}"
dow_part = "EXTRACT(DOW FROM punches.punched_in_at at time zone 'UTC#{utc_diff}') as dow"
So there you have it, hope it helps others.

evaluate difference between 2 dates to make a transition possible

Is this possible to evaluate the duration between a specified date on a form of a workflow, and the system date ? that what I want to do, in order to show (if this possible too) a short message if 1 day occurs since the specified date above, forbidding the transition of the status Closed to Reopened...
Thanks a lot,
Christophe
I think the Script Runner has a validator that does something like this but I can't find it. Then you could write a post function with the Script Runner. Otherwise it's back to creating a custom validator, as described in my book Practical JIRA Plugins (O'Reilly)
You can use the ScriptRunner plugin in addition with the following script in the validator section for the Reopened transition:
Date now = new Date()
Date cfDate = new Date(cfValues['YourCustomField'].getTime())
new Date(now.getYear(), now.getMonth(), now.getDate()).compareTo(cfDate) <= 0
Replace YourCustomField with the name of your custom field. This will ensure that the transition will check whether the current date is beyond the date set in the custom field, and blocks it if it is.
First of all, thank you for your answer.
It works to allow transition when dates are similar, but my purpose was modified by my responsible. He would like to allow the transition if dates are similar or if the duration between them is only 1 day or less.
Example :
System date is 09/07/2013 (Paris)
My date (dd/mm/yyyy format) Transition allowed Why
07/07/2013 NO my date is former to system date
08/07/2013 NO my date is former to system date
09/07/2013 YES my date and system date equals
10/07/2013 YES only 1 day occur between 2 dates
11/07/2013 NO 2 days occur between 2 dates
Here is the code I wrote in order to do that, but it does'nt work (maybe a Java syntax error?) :
Date now = new Date()
Date cfDate = new Date(cfValues['Date de clôture réelle de la demande'].getTime())
new Boolean(((now.getTime() - cfDate) / 86400000) <= 1) && (now.getTime() >= cfDate ))
Excuse me for my english. I'm french, and I try to improve my English.
Thanks a lot.

Resources