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

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);

Related

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

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.

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.

Microsoft Access DateDiff + Difference in time if end time is next day

I have a table with records, where each record has a date column, then a start time column and end time column.
I am trying to do a datediff to get the duration in hours from start to end date with DateDiff('s',[Start Date[,[End Date])/3600.
This works perfectly for End dates that are on same day as date column, but sometimes the end date would be the next day like 12:45 AM. The date diff will give me a large negative number, how do I let it know its next day?
I dont own the data, so not much I can do with the table
Thanks!
Try something like this:
DateDiff('s',[Start Date],DateAdd('d',IIF([End date]<[Start Date],1,0),[End Date]))/3600
It can be done with pure math:
TotalHours = TimeValue(CDate([End Date] - [Start Date] + 1)) * 24

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())

What is the precise definition of JDE's Julian Date format?

I am writing code to convert from a Gregorian date to a JDE (J.D.Edwards) Julian date.
Note: a JDE Julian date is different from the normal usage of the term Julian date.
As far as I can work out from Googling, the definition of a JDE Julian date is:
1000*(year-1900) + dayofyear
where year is the 4-digit year (e.g. 2009), and dayofyear is 1 for 1st January, and counts up all year to either 365 or 366 for 31st December (depending whether this is a leap year).
My question is this: are years before 1900 supported? If so, does the above formula still hold, or should it be this:
1000*(year-1900) - dayofyear
(note minus instead of plus.)
or something else?
Does anyone have a link to the official documentation for this date format?
The JDE Julian date consists of CYYDDD which is Century, Year, Day of year.
Century is zero for 20th e.g. 19XX and one for 21st e.g. 20XX.
The year is two digits.
So 101001 is 1 January 2001
As you can see this will not support dates before 1900.
See this Oracle page for a simple and official explanation: About the Julian Date Format
The "JDE Julian Date Converter" does return a negative value for:
1809/07/23 : -90635
As opposed to the classical Julian Date:
The Julian date for CE 1809 July 23 00:00:00.0 UT is
JD 2381986.50000
Here is a example of JD EDWARDS (AS/400 software) Julian Date, but that is not an "official" documentation and it does not seems to support dates before 1900...
Note: this "ACC: How to Convert Julian Days to Dates in Access and Back" does not support date before 1900 either... as it speaks about an "informal" Julian day, commonly used by government agencies and contractors.
The informal Julian day format used in this article is the ordinal day of a year (for example, Julian day 032 represents February 1st, or the 32nd day of the year).
Variations on informal Julian day formats include using a preceding two-digit year (for example 96032 for 2/1/96) and separating the year with a dash (for example 96-032).
Another, less popular, Julian day format uses a one digit year (for example 6-032). These additional formats do not uniquely identify the century or decade. You should carefully consider the consequences when using these formats; for example, the Julian day 00061 can be interpreted as 3/1/2000 or 3/2/1900.
Update: Sorry, JDE is probably something else. But for reference:
The JDE I know is different. From page 59 in the book
"Astronomical algorithms" (Jean Meeus, ISBN 0-943396-35-2):
"If the JD corresponds to an instant
measured in the scale of Dynamical
Time (or Ephemeris Time), the
expression Julian Ephemeris Day
(JDE) is generally used. (Not JED as
it is sometimes written. The 'E' is a
sort of index appended to 'JD')"
JD and JDE (for the same point in time) are close in value
as the difference UT and ET is on the order of minutes. E.g. ET-UT was 56.86 seconds in 1990 and -2.72 seconds in 1900.
There is also MJD (Modified Julian Day):
MJD = JD - 2400000.5
Zero point for MJD is 1858-11-17, 0h UT.
Note that JD as Julian date is a misnomer. It is
Julian day. The JD has nothing to do with the Julian
calendar. (This is in disagreement with the Wikipedia article, this
is from the author of the book mentioned above, Jean Meeus - a Belgian astronomer specializing in celestial mechanics.)
Maybe off from the question, you can convert in Excel using the following formula:
Convert Julian to Date in Excel
In Cell A2 place a Julian date, like 102324
in Cell B2 place this formula: (copy it in)
=DATE(YEAR("01/01/"&TEXT(1900+INT(A2/1000),0)),MONTH("01/01/"&TEXT(1900+INT(A2/1000),0)),DAY("01/01/"&TEXT(1900+INT(A2/1000),0)))+MOD(A2,1000)-1
The date 11/20/02 date will appear in cell B2
Convert Date to Julian in Excel
In Cell C2 copy this formula:
=(YEAR(B2)-2000+100)*1000+B2-DATE(YEAR(B2),"01","01")+1
This will convert B2 back to 102324
Save the below source code in a source member called JDEDATES. Use the runsqlstm on the first line to create the functions. You can then do things like
select jde2date(A1UPMJ), f.* from f00095 f
and see a real date.
Source:
--RUNSQLSTM SRCFILE(qtxtsrc) SRCMBR(JDEDATES) COMMIT(*NONE) NAMING(*SQL)
-- jde 2 date
create function QGPL/jde2date ( d decimal(7,0))
returns date
language sql
deterministic
contains sql
SET OPTION DATFMT=*ISO
BEGIN
if d=0 then return null;
else
return date(digits(decimal(d+1900000,7,0)));
end if;
end; -- date 2 jde
create function QGPL/date2jde ( d date)
returns decimal(7,0)
language sql
deterministic
contains sql
SET OPTION DATFMT=*ISO
BEGIN
if d is null then return 0;
else
return (YEAR(D)-1900)*1000+DAYOFYEAR(D);
end if;
end ;
Several years late to the party, but for other folks like me that find yourselves working with legacy systems like this, I hope some of my java snippets can help. I'm leveraging the fact that you can convert this CYYDDD format into yyyyDDD format and parse based on that.
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.SimpleDateFormat;
String jdeJulianDate = "099365"; //Testing with December 31, 1999
// Compile what the year number is
int centIndex = Integer.parseInt(jdeJulianDate.substring(0,1));
int yearIndex = Integer.parseInt(jdeJulianDate.substring(1,3));
int yearNumber = 1900 + (100 * centIndex) + yearIndex;
// Put the year number together with date ordinal to get yyyyDDD format
String fullDate = String.valueOf(yearNumber) + jdeJulianDate.substring(3,6);
// Date parsing, so need to wrap in try/catch block
try {
Date dt = new SimpleDateFormat("yyyyDDD").parse(fullDate);
// Validate it parses to a date in the same year...
Calendar cal = new GregorianCalendar();
cal.setTime(dt);
if (cal.get(Calendar.YEAR) != yearNumber) {
// Cases happen where things like 121366 (should be invalid) get parsed, yielding 2022-01-01.
// Throw exception or what-not here.
}
}
catch (Exception e) {
// Date parsing error handling here
}
A sample of VBA code to convert back and forth between JDE Julian Date and Gregorian:
Public Const Epoch = 1900
Public Const JDateMultiplier = 1000
Public Const FirstJan = "01/01/"
Public Function Julian2Date(ByVal vDate As Long) As Date
Dim Year As Long
Dim Days As Long
Dim SeedDate As Date
' Day Number
Days = vDate - (Int(vDate / JDateMultiplier) * JDateMultiplier) - 1
' Calendar Year
Year = ((vDate - Days) / JDateMultiplier) + Epoch
' First Day of Calendar Year
SeedDate = CDate(FirstJan + CStr(Year))
' Add Number of Days to First Day in Calendar Year
Julian2Date = DateAdd("d", Days, SeedDate)
End Function
Public Function Date2Julian(ByVal vDate As Date) As Long
Dim JYear As String
Dim BeginDate As Date
Dim JDays As Long
' Calendar Year
JYear = Format(Year(vDate), "0000")
' First Day of Calendar Year
BeginDate = CDate(FirstJan + JYear)
' Day Number
JDays = DateDiff("d", BeginDate, vDate) + 1
' Add Number of Days to Year Number
Date2Julian = ((CLng(JYear) - Epoch) * JDateMultiplier) + JDays
End Function
I have tried to make it as clear and simple as possible, and to this end I have intentionally left out any error trapping. However, you should be able to add the code to a VBA module and call them directly from your own code.
I also include some useful snippets of T-SQL:
Todays Date as JDE Julian Date:
(datepart(yy,getdate())-1900) * 1000 + datepart(dy, getdate())
Convert JDE Julian Date to Gregorian (DD/MM/YYYY), replace XXXXXX with the column name containing the JDE Julian Date:
convert (varchar, dateadd (day,convert (int, right(XXXXXX,3)) - 1, convert (datetime, ('1/1/' + convert ( varchar, (cast(left(right(XXXXXX+1000000,6),3) as varchar) + 1900))))),103)
If you require a different Gregorian format, replace the 103 value (right at the end) with the applicable value found here: https://msdn.microsoft.com/en-us/library/ms187928.aspx
I have an easy way for C using time now and epoch 1970, 01, 01 midnight if anybody is interested.
But this is for Julian Day Numbers which is not the same as JDE but they are similar in respect to using math to compute days and I'm sure this idea could be adapted for JDE. Sometimes people just confuse the two like I do. Sorry. But still this is an example of using a time reference which should always be done and since most computers use this it would be just as easy for us not to get too bogged down in dates and just use days before or after this epoch.
Since JDE is now owned by Oracle, they also now support Julian_Day. see:
https://docs.oracle.com/javase/8/docs/api/java/time/temporal/JulianFields.html
#include <stdio.h>
#include <time.h>
#define EPOCH (double) 2440587.5 /* Julian Day number for Jan. 01, 1970 midnight */
int main ()
{
double days = time(0)/86400.0;
printf ("%f days since January 1, 1970\n", days);
printf ("%f\n", days + EPOCH);
return 0;
}
Wow, there's a lot of complicated code in some of these answers just to convert to and from JDE julian dates. There are simple ways in Excel and VBA to get there.
FROM JULIAN
Excel (assuming julian date is in A1):
=DATE(1900+LEFT(A1,LEN(A1)-3),1,RIGHT(A1,3))
VBA (from julian date, j, stored as String):
d = DateSerial(1900 + Left$(j, Len(j) - 3), 1, Right$(j, 3))
VBA (from julian date, j, stored as Long):
d = DateSerial(1900 + Left$(j, Len(CStr(j)) - 3), 1, Right$(j, 3))
TO JULIAN
Excel (assuming date is in A1):
=(YEAR(A1)-1900)*1000+A1-DATE(YEAR(A1),1,0)
VBA (to a Long, j):
j = (Year(d) - 1900) * 1000 + DatePart("y", d)