Named query to show results by date (Year, month, day) in Grails 3.2.10 - date

Given this domain:
class Burger{
String description
Date dateCreated
}
Currently, I have this namedQuery
queryOnDateCreated {Date dateArgument ->
eq 'dateCreated', dateArgument
}
I need a query that allows me find all the objects in the domain Burger with a specific dateCreated only taking into accountYear, Month and day (of month), while ignoring hours, minutes, seconds, miliseconds.

After some additional research, I found a solution which I'm going to share in case it helps someone else:
The named query needs to be as follows:
queryOnDateCreated {Date dateArgument ->
def dateArgumentIntervalEnd = DateUtils.addMilliseconds(dateArgument + 1, - 1)
between 'dateCreated', dateArgument, dateArgumentIntervalEnd
}
Explanation:
The "between" criteria returns every object in the domain whose date is between the interval given.
Since dateArgument is a Date created only with Year, Month and Day, it's time should be 00:00:00:000 (the first moment of the day).
Furthermore, "dateArgument + 1" holds the value of the next day (at the same time), which is why the substraction of 1 millisecond is required, that way "dateArgumentIntervalEnd" will hold the value of the same Year, Month and Day of "dateArgument" but the time will be 23:59:59:999 holding an interval of the whole day.

Related

Calculate a Reference Date in DAX

Trying to nail down the syntax for a pretty straightforward problem.
I have a table called Events and a full-feature DATES table with a relationship between the Dates[Date] field.
Using the event name as a slicer, I trying to create a [First Monday] measure that will return the date of the first Monday of the month.
So for example, if my event date was 2/14/19, [First Monday] would return 2/4/19.
Your Date table needs to contain 2 columns:
Year-Month: for example, "2018-01"
Weekday Number: for example, 1 (for Monday); or Weekday Name (i.e, "Monday")
Then:
First Monday =
CALCULATE( MIN('Date'[Date]),
ALL('Date'),
VALUES('Date'[Year-Month]),
'Date'[Weekday Name] = "Monday")
How it works:
First, we need to access all dates in the Date table, so we use ALL()
Second, we need to see only dates for the current context year and month, for which we can use VALUES()
Third, for each month we only want Mondays, hence Date[Weekday] = "Monday"
All this unfiltering/filtering generates a set of Mondays for the Year-Month visible in the current filter context. All we need to do now is to find the earliest of the Mondays using Min(Date).

How to split timestamp field into Year, Month and Day, etc?

I have a timestamp field which has this definition:
Time interval: the beginning of the time interval expressed as the
number of millisecond elapsed from the Unix Epoch on January 1st, 1970
at UTC. The end of the time interval can be obtained by adding 600000
milliseconds (10 minutes) to this value. TYPE: numeric
I would like to split this field into Year, Month, Day of Month, Day of Week, Week Number.
It appears that I would need to use a Derive field with a Formula. But as a user new to the SPSS world, it isn't clear to me how I would use the derive field to do this.
The equivalent in pandas is:
df['Datetime'] = pd.to_datetime(df['Time interval'].astype(int))
df['Year'] = df['Datetime'].dt.year
df['Month'] = df['Datetime'].dt.month
df['Day'] = df['Datetime'].dt.day
df['DayOfWeek'] = df['Datetime'].dt.dayofweek
Do you want to create the 5 variables in separate, right?
For create:
**1) Year - Use a derive node and call the new variable as 'Year' with the syntax: "datetime_year(field)" -> will extract the year in numbers (2012)
2) Month- Use a derive node and call the new variable as 'Month' with the syntax: "datetime_month(field)" -> will extract the month in numbers (1 to 12)
3) Day of Month- Use a derive node and call the new variable as 'DayMonth' with the syntax: "datetime_day(field)" -> will extract the date of the month in numbers (1 to 31)
4) Day of Week - Use a derive node and call the new variable as 'DayWeek' with the syntax: "datetime_weekday(field)" -> will extract the weekday in numbers (1 to 7)
5) Week Number - Use a derive node and call the new variable as 'WeekNumb' with the syntax: "date_iso_week(field)" -> ISO 8601 (it's the only function that I never used in your list).**
Also, you can check others expressions inside the derive node tab, just select all functions and make some tests.
IBM Ref
I hope to have been helpful.

Is it possible to find data from MySQL by month using JPA and java.time.LocalDate date format?

I creating an application, for that I need to find data by month using JPA and java.time.LocalDate. So, is it possible to retrieve data by month from mysql?
Thanks in advance for help.
First find start and end date of month and use between method of JPA to find data of current month.
LocalDate start = LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).withDayOfMonth(1);
LocalDate end = LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).plusMonths(1).withDayOfMonth(1).minusDays(1);
In Repository
List<Object> findByCreatedateGreaterThanAndCreatedateLessThan(LocalDate start,LocalDate end);
Its better to use the between keyword, it makes things allot shorter.
List<Object> findByCreatedateBetween(LocalDate start,LocalDate end);
Also if you want to use the LocalDate or LocalDateTime objects with Spring Data you should use the converter class Jsr310JpaConverters or else the documents will be stored as Blobs instead of Dates (which is bad for portability of the database). Please see this tutorial on how to implement the Converter.
https://www.mkyong.com/spring-boot/spring-boot-spring-data-jpa-java-8-date-and-time-jsr310/
tl;dr
YearMonth.now( ZoneId.of( "Pacific/Auckland" ) ) // Get current month for particular time zone.
.atDayOfMonth( 1 ) // Get the first date of that month.
.plusMonths( 1 ) // Get first of next month for Half-Open query.
Details
Assuming your column in MySQL is of DATE type…
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
Time zone
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
YearMonth
The YearMonth class represents an entire month. Getting the current month requires a time zone as discussed above. Around the beginning/ending of the month, the current moment could be “next” month in Auckland New Zealand while still “previous” month in Kolkata India.
YearMonth currentMonth = YearMonth.now( z ) ;
Get the first date of the month.
LocalDate start = currentMonth.atDayOfMonth( 1 ) ;
Half-Open
Generally best to use the Half-Open [) approach to defining a span of time, where the beginning is inclusive while the ending is exclusive. So defining a month means starting with the first date of the month and running up to, but not including, the first date of the following month.
LocalDate stop = start.plusMonths( 1 ) ;
Query
Do not use the BETWEEN command in SQL as it is fully closed [], both beginning and ending being inclusive. Half-Open uses >= & < logic.
SELECT when FROM tbl
WHERE when >= start
AND when < stop
;
it's also useful
#Query("from PogWorkTime p where p.codePto = :codePto and month(p.dateApply) = :month and year(p.dateApply) = :year")
Iterable<PtoExceptWorkTime> findByCodePtoAndDateApply_MonthAndDateApply_Year(#Param("codePto") String codePto,#Param("month") int month, #Param("year") int year);

Qlikview Automate past 12 months selection

I have a combo chart which shows the average days it took for a person to pay their bill.
The Dimension of the Chart is = [Pay Month Year last 12 months]
There are no Dimension limits
There is 1 expression which is called Average and its definition is:
avg({< InvoicefromSqlType = {'Invoices'},[Is Invoice Paid] = {'Y'},[Is Positive Amount] = {'Y'},[Is Paid last 12 months] = {'Y'},DueGroups=,[Pay Month Year last 12 months]=>}[Days to Pay])`
Its is sorted by expression, which is [Pay Month Year last 12 months]
Now the above fields are built up like this:
[Pay Month Year last 12 months]
If([Pay Date] >= '$(vPeriodS12)',[Pay Month year]) as [Pay Month Year last 12 months],
PayLoadOrder:
Load * Inline [Pay Month Year last 12 months
May-2014
Jun-2014
Jul-2014
Aug-2014
Sep-2014
Oct-2014
Nov-2014
Dec-2014
Jan-2015
Feb-2015
Mar-2015
Apr-2015
May-2015
];
Now what is happening is every month when it reaches the end, the next month is needing to be manually added and the first month removed (e.g. in the above I would delete the line May-2014 and at the end add the line Jun-2015)
Also if there are months defined which there is no data for yet i.e. you have Jun-2015 hard coded and the current month this May-2015 then Jun-2015 will show data from 2014 and the order of the months will get mixed up.
What I want to do is completely remove the need to hard code the months above and have this done its self.
If there are any more information you need let me know
Instead of using a "sort order" table that you may have to manually update, it may be worth doing the following:
Create a new field derived from [Pay Date] that returns a month and year that you can sort. For example:
dual(date(makedate(year([Pay Date]),num(month([Pay Date]))),'MMM-yyyy'),
year([Pay Date]) * 100 + num(month([Pay Date]))) as PayMonthYear
Here, the dual function allows you to associate a different representation of a field value to its underlying value. For example, here we set the underlying data to be the year of [Pay Date] added to the month, but state that it should be displayed as MMM-yyyy. For example, internally, QV still sees the value 201502, but displays it as Feb-2015. This means you can sort it correctly based on its underlying value.
Using dual is a big topic, please consult the built-in help for QV for more information.
Change your chart dimension from [Pay Month Year last 12 months] to use PayMonthYear and set the sort to ascending. This would then mean that your months would be sorted correctly, even if a new month was added.
Remove table PayLoadOrder from your script.
Alternative Method
An alternative would be to use a calendar table which joins on your Pay Date field. This would achieve the same thing, however, you could also integrate your "year to date" indicator into the calendar as well and remove it from your main table. An example I quickly threw together is shown below:
MinMax:
LOAD
Max([Pay Date]) AS MaxDate,
Min([Pay Date]) AS MinDate
RESIDENT MyData;
LET varMinDate = Num(Peek('MinDate',0,'MinMax')); // 0 is first record
LET varMaxDate = Num(Peek('MaxDate',-1,'MinMax')); // -1 is last record
LET varToday = Num(Today());
MasterCalendar:
LOAD
monthstart([Pay Date]) >= monthstart(AddMonths(Today(),-12)) as PaidInLast12MonthsFlag,
dual(date(makedate(year([Pay Date]),num(month([Pay Date]))),'MMM-yyyy'),year([Pay Date]) * 100 + num(month([Pay Date]))) as PayMonthYear
[Pay Date];
LOAD
date($(varMinDate) + RecNo() - 1,'DD/MM/YYYY') as [Pay Date]
AUTOGENERATE num($(varMaxDate)) - num($(varMinDate)) + 1;
DROP TABLE MinMax;
So, in the above, the field PaidInLast12MonthsFlag is equal to -1 if the value of the [Pay Date] field occurs in the last 12 months, 0 otherwise. You could use this in your set analysis expression as a filter. Furthermore, you can use PayMonthYear as your chart dimension.

MS Access 2010 (Design View): return Monday of the current week with Monday as 1st day of the week

I need to make my Access query always return the Monday of the current week. I have seen a few solutions on Google/StackOverflow but they are written in SQL and I am a beginner in creating Access queries (I am using the Design view to make them).
Goal: The week should be considered as M T W T F S S. Then, the query should always return the Monday of the current week. Therefore, if it is Sunday, it should still return the Monday before, NOT the next week's Monday. Can anyone explain how to do this using the Design View in Access 2010?
Keep in mind that in this context we are working with dates, so if we do Date() - 1, we will get 1 day prior to today.
Date() ~ Today's date
DatePart(
"w" - Weekday
Date() - Today's date
2 - vBMonday (Access assumes Sunday is the first day of the week, which is why this is necessary.)
1 - vbFirstJan1 - This gets into using the first week of the year. We could have omitted this, as 1 is the default.
)
-1 - Subtract 1 from the DatePart value.
Values
Date() = 4/27/2015 (at time of this writing)
DatePart("w",Date(),2,1) = 1
DatePart("w",Date(),2,1)-1 = 0
So we have Date()-0... Okay, what's so great about that? Well, let's look at a more useful scenario where today's date is a day other than Monday.
Let's act like today is 4/28/2015 (Tuesday)
Date() = 4/28/2015
DatePart("w",Date(),2,1) = 2
DatePart("w",Date(),2,1)-1 = 1
So, from the outside, in; give me the current weekday value. (1 = Monday, 2 = Tuesday, etc.), and subtract 1 from that -> that's how many days we need to subtract from the current date to get back to the weekday value of 1 (Monday).
Here's a function that will do this:
Public Function DatePrevWeekday( _
ByVal datDate As Date, _
Optional ByVal bytWeekday As VbDayOfWeek = vbMonday) _
As Date
' Returns the date of the previous weekday, as spelled in vbXxxxday, prior to datDate.
' 2000-09-06. Cactus Data ApS.
' No special error handling.
On Error Resume Next
DatePrevWeekday = DateAdd("d", 1 - Weekday(datDate, bytWeekday), datDate)
End Function
As vbMonday is 2 and your date is today, you can use the core expression in a query:
PreviousMonday: DateAdd("d",1-Weekday(Date(),2),Date())