LastFullWeek starting with monday in crystal reports - date

When using LastFullWeek i get the last Sunday - Saturday week, but for my reports i want the last Monday - Sunday week.
Is there any simple way to get this behaviour, or do I have to write my own function for it (which isn't that hard, but unconvenient for such a common date span.)

custom function:
//LastFullWeekEx
Function (DateVar date, Optional NumberVar firstDayOfWeek := crSunday)
(date - DayOfWeek(date, firstDayOfWeek)) - 6 TO (date - DayOfWeek(date, firstDayOfWeek))
usage:
// use with non-volatile DataDate and Sunday
{TABLE.DATE} IN LastFullWeekEx(DataDate)
// use with non-volatile DataDate and Monday
{TABLE.DATE} IN LastFullWeekEx(DataDate, crMonday)
testing:
// should return True
( Minimum(LastFullWeek) = Minimum(LastFullWeekEx(DataDate, crSunday)) ) AND
( Maximum(LastFullWeek) = Maximum(LastFullWeekEx(DataDate, crSunday)) )

Instead of using
{DATE} in LastFullWeek
use the form
{DATE}-1 in LastFullWeek

The code, if no better answer comes along, for others who find this question through the search engine:
{DATE} >= currentdate - dayofweek(currentdate, crMonday) - 6 AND
{DATE} < currentdate - dayofweek(currentdate, crMonday) + 1

You have no other choice than to use a custom formule as Crystal Reports uses fixed week settings (US). So a week is Sunday to Saturday and DayOfWeek starts with Sunday (value/index 1).

Add +1 to LastFullWeek min and max:
DateVar Start := Minimum(LastFullWeek)+1; //Monday
DateVar End := Maximum(LastFullWeek)+1; //Sunday
Edit: Since LastFullWeek always takes Sunday as the first day of the week, we need to check if the current day is Sunday. If so, we need to subtract a week:
// Check if the current day is Sunday
IF (DAYOFWEEK(CurrentDate) = 1)
THEN (
Start := Start - 7;
End := End - 7
);
Example: Date range to string
StringVar LastWeekRange := ToText(Start) + " - " + ToText(End);
LastWeekRange;
Return example: "MM/DD/YYYY - MM/DD/YYYY"
Example: Selecting all dates within date range
{datefield} >= Start and {datefield} <= End;

Related

write a function that generates a list of last days of each month for the past n months from current date

I am trying to create a list of the last days of each month for the past n months from the current date but not including current month
I tried different approaches:
def last_n_month_end(n_months):
"""
Returns a list of the last n month end dates
"""
return [datetime.date.today().replace(day=1) - datetime.timedelta(days=1) - datetime.timedelta(days=30*i) for i in range(n_months)]
somehow this partly works if each every month only has 30 days and also not work in databricks pyspark. It returns AttributeError: 'method_descriptor' object has no attribute 'today'
I also tried the approach mentioned in Generate a sequence of the last days of all previous N months with a given month
def previous_month_ends(date, months):
year, month, day = [int(x) for x in date.split('-')]
d = datetime.date(year, month, day)
t = datetime.timedelta(1)
s = datetime.date(year, month, 1)
return [(x - t).strftime('%Y-%m-%d')
for m in range(months - 1, -1, -1)
for x in (datetime.date(s.year, s.month - m, s.day) if s.month > m else \
datetime.date(s.year - 1, s.month - (m - 12), s.day),)]
but I am not getting it correctly.
I also tried:
df = spark.createDataFrame([(1,)],['id'])
days = df.withColumn('last_dates', explode(expr('sequence(last_day(add_months(current_date(),-3)), last_day(add_months(current_date(), -1)), interval 1 month)')))
I got the last three months (Sep, oct, nov), but all of them are the 30th but Oct has Oct 31st. However, it gives me the correct last days when I put more than 3.
What I am trying to get is this:
(last days of the last 4 months not including last_day of current_date)
daterange = ['2022-08-31','2022-09-30','2022-10-31','2022-11-30']
Not sure if this is the best or optimal way to do it, but this does it...
Requires the following package since datetime does not seem to have anyway to subtract months as far as I know without hardcoding the number of days or weeks. Not sure, so don't quote me on this....
Package Installation:
pip install python-dateutil
Edit: There was a misunderstanding from my end. I had assumed that all dates were required and not just the month ends. Anyways hope the updated code might help. Still not the most optimal, but easy to understand I guess..
# import datetime package
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta
def previous_month_ends(months_to_subtract):
# get first day of current month
first_day_of_current_month = date.today().replace(day=1)
print(f"First Day of Current Month: {first_day_of_current_month}")
# Calculate and previous month's Last date
date_range_list = [first_day_of_current_month - relativedelta(days=1)]
cur_iter = 1
while cur_iter < months_to_subtract:
# Calculate First Day of previous months relative to first day of current month
cur_iter_fdom = first_day_of_current_month - relativedelta(months=cur_iter)
# Subtract one day to get the last day of previous month
cur_iter_ldom = cur_iter_fdom - relativedelta(days=1)
# Append to the list
date_range_list.append(cur_iter_ldom)
# Increment Counter
cur_iter+=1
return date_range_list
print(previous_month_ends(3))
Function to calculate date list between 2 dates:
Calculate the first of current month.
Calculate start and end dates and then loop through them to get the list of dates.
I have ignored the date argument, since I have assumed that it will be for current date. alternatively it can be added following your own code which should work perfectly.
# import datetime package
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta
def gen_date_list(months_to_subtract):
# get first day of current month
first_day_of_current_month = date.today().replace(day=1)
print(f"First Day of Current Month: {first_day_of_current_month}")
start_date = first_day_of_current_month - relativedelta(months=months_to_subtract)
end_date = first_day_of_current_month - relativedelta(days=1)
print(f"Start Date: {start_date}")
print(f"End Date: {end_date}")
date_range_list = [start_date]
cur_iter_date = start_date
while cur_iter_date < end_date:
cur_iter_date += timedelta(days=1)
date_range_list.append(cur_iter_date)
# print(date_range_list)
return date_range_list
print(gen_date_list(3))
Hope it helps...Edits/Comments are welcome - I am learning myself...
I just thought a work around I can use since my last codes work:
df = spark.createDataFrame([(1,)],['id'])
days = df.withColumn('last_dates', explode(expr('sequence(last_day(add_months(current_date(),-3)), last_day(add_months(current_date(), -1)), interval 1 month)')))
is to enter -4 and just remove the last_date that I do not need days.pop(0) that should give me the list of needed last_dates.
from datetime import datetime, timedelta
def get_last_dates(n_months):
'''
generates a list of lastdates for each month for the past n months
Param:
n_months = number of months back
'''
last_dates = [] # initiate an empty list
for i in range(n_months):
last_dates.append((datetime.today() - timedelta(days=i*30)).replace(day=1) - timedelta(days=1))
return last_dates
This should give you a more accurate last_days

Get first day and last day dates of month of selected date in Marklogic

I am trying to get first day and last day dates of any selected date using MarkLogic.
Example:
let $date := xs:date("2018-08-24")
let $firstDay := "*Should be 1st day of month - of $date*"
let $lastDay := "*Should be last day of month - of $date*"
return ("$firstDay:",$firstDay,"$lastDay:",$lastDay)
Expected Output dates:
$firstDay: 2018-08-01
$lastDay: 2018-08-31
I can able to get this dates by using functx:first-day-of-month($date) and
functx:last-day-of-month($date) but I wanted to know is there any API or alternative option provided by MarkLogic
You can compute this directly using standard XQuery duration arithmetic:
let $date := xs:date("2018-08-24")
let $one-day := xs:dayTimeDuration('P1D')
let $one-month := xs:yearMonthDuration('P1M')
(: subtract days to get to the 1st of the month :)
let $firstDay := $date - (fn:day-from-date($date) - 1) * $one-day
(: get the 1st of the next month and then subtract one day :)
let $lastDay := $firstDay + $one-month - $one-day
return ("$firstDay:",$firstDay,"$lastDay:",$lastDay)

Qlikview - arrayList

i need to calculate difference between two date excluding sunday. I have table with dates and i need to calculate number of dates of repeated days from last date.
if i have dates like that
27-05-2017
29-05-2017
30-05-2017
I use this code in script
date(max(Date)) as dateMax,
date(min(Date)) as dateMin
And i get min date = 27-05-2017 and max date = 30-05-2017 then i use in expressions
=floor(((dateMax - dateMin)+1)/7)*6 + mod((dateMax - dateMin)+1,7)
+ if(Weekday(dateMin) + mod((dateMax - dateMin)+1,7) < 7, 0, -1)
And get result 3 days. Thats OK, but the problem is if I have next dates:
10-05-2017
11-05-2017
27-05-2017
29-05-2017
30-05-2017
When use previously code I get min date = 10-05-2017 and max date = 30-05-2017 and result 18, but this is not OK.
I need to count only dates from
27-05-2017
29-05-2017
30-05-2017
I need to get max date and go throw loop repeated dates and if have brake to see is that date sunday if yes then step that date and continue to count repeated dates and if i again have break and if not sunday than close loop and remember number of days.
In my case instead of 18 days i need to get 3 days.
Any idea?
I'd recommend you creating a master calendar in the script where you can apply weights or any other rule to your days. Then in your table or app you can just loop through the dates or perform operations and sum their weights (0: if sunday, 1: if not). Let's see an example:
// In this case I'll do a master calendar of the present year
LET vMinDate = Num(MakeDate(year(today()),1,1));
LET vMaxDate = Num(MakeDate(year(today()),12,31));
Calendar_tmp:
LOAD
$(vMinDate) + Iterno() - 1 as Num,
Date($(vMinDate) + Iterno() - 1) as Date_tmp
AUTOGENERATE 1 WHILE $(vMinDate) + Iterno() - 1 <= $(vMaxDate);
Master_Calendar:
LOAD
Date_tmp AS Date,
Week(Date_tmp) as Week,
Year(Date_tmp) as Year,
Capitalize(Month(Date_tmp)) as Month,
Day(Date_tmp) as Day,
WeekDay(Date_tmp) as WeekDay,
if(WeekDay = '7',0,1) as DayWeight //HERE IS WHERE YOU COULD DEFINE A VARIABLE TO DIRECTLY COUNT THE DAY IF IT IS NOT SUNDAY
'T' & ceil(num(Month(Date_tmp))/3) as Quarter,
'T' & ceil(num(Month(Date_tmp))/3) & '-' & right(year(Date_tmp),2) as QuarterYear,
date(monthStart(Date_tmp),'MMMM-YYYY') as MonthYear,
date(monthstart(Date_tmp),'MMM-YY') as MonthYear2
RESIDENT Calendar_tmp
ORDER BY Date_tmp ASC;
DROP Table Calendar_tmp;

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

Correct ISO week numbering in Crystal Reports XI

How can I get the ISO-8601 week number of a given date in Crystal Reports XI?
Crystal Reports supports the DatePart-function which can give you the ISO week number of a given date.
NumberVar week := DatePart("ww", date, crMonday, crFirstFourDays);
However, in Crystal Reports XI there is a bug that gives erronous results round new year. The best solution is probably to create an own function getISOWeekNumber:
Function (optional DateVar d := CurrentDate)
NumberVar week := DatePart("ww", d, crMonday, crFirstFourDays);
// Correct for that CR doesn't handle the fact that the last days of a year can belong to week 1 of the next year:
if week = 53 and DatePart("ww", cDate(year(d) + 1, 1, 1), crMonday, crFirstFourDays) = 1 then
week := 1
// A bug in CR makes DatePart return values like 9363 for days in January that belongs to the last week of the previous year.
else if week > 53 then
week := DatePart("ww", cDate(year(d) - 1, 12, 31), crMonday, crFirstFourDays);
week;
To get the "week-year" of a specific date, you could then use the following function:
// Returns the year to which the ISO week of the specified date belongs.
// E.g. 2012-12-31 will return 2013, as that date belongs to week 1 of 2013.
Function (optional DateVar d := CurrentDate)
NumberVar week := getISOWeekNumber (d);
if week = 1 and month(d) = 12 then
year(d) + 1
else if week > 10 and month(d) = 1 then
year(d) - 1
else
year(d);