Using the DateDiff function in VBA to get number of days between 2 dates - datediff

so I'm trying to get 2 dates in an excel sheet and use the DateDiff function to get the number of days between the 2 dates. I am essentially adding the number of days together and dividing by the the number of rows to get and average amount of days. So far I have it to where the total amount of days for every row gets added together and is displayed on column "E" and the number of rows is placed on column "F". I know I am close because at one point it worked but I was dumb and changed something and now i does not. here is my code and the excel sheet.
Sub GetDays()
Range("C1").Select
Do Until ActiveCell.Value = ""
date1 = DateValue(ActiveCell.Offset(1, 0).Value)
date2 = DateValue(ActiveCell.Offset(1, 0).EntireRow.Cells(1, "D").Value)
DayCount = DateDiff("d", date1, date2) + DayCount
ActiveCell.Offset(1, 0).EntireRow.Cells(1, "E").Value = DayCount
StudentCount = StudentCount + 1
ActiveCell.Offset(1, 0).EntireRow.Cells(1, "F").Value = StudentCount
ActiveCell.Offset(1, 0).Select
Loop
End Sub!
Here is a snippet of the sheet

The issue I discovered when testing your code is that your loop is comparing to the ActiveCell value to determine when to exit, but then your code is operating on the cell below ActiveCell, as a result of the Offset(1,0) call. So when your loop is on the last line of data, ActiveCell.Value = "3/25/2015 10:52", but your next line of code is trying to populate date1 with the DateValue of a null since it is offset down one row. This throws a Type Mismatch error.
I've adjusted your code below, this works for me:
Sub GetDays()
Range("C1").Select
Do Until ActiveCell.Value = ""
date1 = DateValue(ActiveCell.Value)
date2 = DateValue(ActiveCell.Offset(0, 1).Value)
DayCount = DateDiff("d", date1, date2) + DayCount
ActiveCell.Offset(0, 2).Value = DayCount
StudentCount = StudentCount + 1
ActiveCell.Offset(0, 3).Value = StudentCount
ActiveCell.Offset(1, 0).Select
Loop
End Sub
I adjusted the offset command so that we are looking at the same row at all times each loop. I replaced the "EntireRow.Cells(1, "D")" sections by just using the column integer in Offset().
You may need to change the second line to: Range ("C2").Select for my code to work, depending on if your data starts on row 1 or row 2.

Related

select end of month and make it a string in pyspark

I want to create a loop in pyspark where I give a month and it should select the table on the end of the month and the end of month of the previous month.
The selection of the month is made with a string.
So I give '201901' and it should select '20190131' and '20181231'.
And if possible it should run automatically and select the end of previous month from today and end of previous previous month of today.
So today we are 2020-05-07 so it should select '20200430' and '20200331'.
def selectTables(date):
i = 0
for i in range(len(date)):
recentDate = .... # should be for the first iteration '20190131'
previousDate = .... # should be for the first iteration '20181231'
recent = spark.read.parquet('table.parquet/date=' + recentDate[i])
previous = spark.read.parquet('table.parquet/date=' + previousDate[i])
selectTables(['201901', '201902'])
Use add_months,last_day in built spark functions to get last day.
Example:
date='201901'
recentDate=spark.sql("select string(last_day(to_date('{}','yyyyMM')))".format(date)).collect()[0][0]
#u'2019-01-31'
previousDate=spark.sql("select string(last_day(add_months(to_date('{}','yyyyMM'),'-1')))".format(date)).collect()[0][0]
#u'2018-12-31'

compare parameter dates with dataset date field in custom code

I need to create a report that displays net working days, excluding holidays. This needs to be a calculation or a calculated field. I have custom code to get the weekends accounted for, and have a Holiday dataset that has all the holidays I need to look for in it.
I have set up a hidden parameter on the report for my Holiday dates. The code below runs, but I get a #Error. As you can see have tried extracting and comparing the Year, Month and Day separately, as I thought it was maybe a date/time issue. That still produced #Error.
Function NumWorkDays(ByRef startDate As Date, ByRef endDate As Date) as Integer
dim i as integer
dim x as integer
dim totalDays as Integer
dim WeekendDays as Integer
dim HolidayDays as integer
dim sDate as Date
dim numWeekdays as Integer
numWeekdays = 0
WeekendDays = 0
HolidayDays = 0
sDate=startDate
totalDays = DateDiff(DateInterval.Day, startDate , endDate ) + 1
for i = 1 to totalDays
if DatePart(dateinterval.weekday,sDate ) = 1 then
WeekendDays = WeekendDays + 1
end if
if DatePart(dateinterval.weekday, sDate ) = 7 then
WeekendDays = WeekendDays + 1
end if
sDate = DateAdd("d", 1, sDate )
next i
sDate=startDate
for x = 1 to totalDays
if DatePart(dateinterval.weekday,sDate ) <> 1 or
DatePart(dateinterval.weekday,sDate ) <> 7 then
for i = 1 to Report.Parameters!HolidayParam.Count()
if Year(Report.Parameters!HolidayParam.Value(i))=Year(sDate) and
Month(Report.Parameters!HolidayParam.Value(i))=Month(sDate) and
Day(Report.Parameters!HolidayParam.Value(i))= Day(sDate) then
HolidayDays = HolidayDays + 1
Exit For
End if
next i
end if
sDate = DateAdd("d", 1, sDate )
next x
numWeekdays = totalDays - WeekendDays -HolidayDays
return numWeekdays
End Function
Just looking for ideas as to where I have gone wrong! Thank you!
Okay, I got this. Being new to SSRS I had a difficult time not being able to step through the custom code or put in breakpoints to display values as they occurred! It was simple, it needed to be a multi-valued parameter. I did not check that as I was keeping it hidden, it didn't strike me that it needed that.
I discovered the problem by putting a text box in a Report Header and simply displaying the count of my parameter. When it showed "1", I knew I had the problem!
The updated code snippet is (all the rest remained the same):
for i = 0 to Report.Parameters!HolidayParam.Count()-1
if Report.Parameters!HolidayParam.Value(i))=sDate then
HolidayDays = HolidayDays + 1
Exit For
End if
next i

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;

Which Months Fall Between Any Two Dates?

I get show months only on date interval, not days.
For i=initDate to endDate
response.write month(i)
next
in this case the result is: 5555555666666667777777......
Is repeat months for each day in interval, but i get display result only months.
For example: 5,6,7,8,9,10,11,12...
Think #John is on the right track with their answer.
But couldn't you simplify the approach by getting the start and end month from your initDate and endDate variables and stepping through the months?
Something like;
Dim initMonth, endMonth
initMonth = Month(initDate)
endMonth = Month(endDate)
For i = initMonth To endMonth
Response.Write i
Next
If you are confident that the initDate and endDate are always Date values you could simplify it further.
For i = Month(initDate) To Month(endDate)
Response.Write i
Next
I'm not sure I understood but maybe this will help. It stores the last month displayed in a variable (lastMonth) and only displays the month if it has changed. It shows the first month because lastMonth is set to zero when created and there should never be a month in the loop of zero.
Dim lastMonth
lastMonth = 0
For i=initDate to endDate
If lastMonth <> Month(i) Then
response.write month(i)
lastMonth = Month(i)
End If
next

PostgreSQL, getting min and max date from text column

I have such situation in table:
1 01.02.2011
2 05.01.2011
3 06.03.2012
4 07.08.2011
5 04.03.2013
6 06.08.2011
7
8 02.02.2013
9 04.06.2010
10 10.10.2012
11 04.04.2012
where first column is id (INT) and second column is TEXT in which may be written date in format 'dd.mm.yyyy'.
I would like to get:
1) lowest entered date in whole table and highest entered date in whole table.
2) lowest entered date in year 2012 and highest entered date in year 2012.
Lowest and highest date in year may be a same (like for year 2010) or field may be empty (like in row 7).
I am tying to use TO_TIMESTAMP but unsuccessfully.
Example:
SELECT (TO_TIMESTAMP(mydatetxt, 'DD.MM.YYYY'))
FROM " & myTable & "
ORDER BY (TO_TIMESTAMP(mydatetxt, 'DD.MM.YYYY')) ASC LIMIT 1
Also with BETWEEN I don't get wanted result.
How to write those two queries?
SOLUTION:
Thanks for all suggestions.
Igor's solution is most suitable and simple enough for me.
Dim sqlText As String = "SELECT min(to_date(nullif(mydate,''), 'DD.MM.YYYY')) FROM " & mytable
cmd1 = New NpgsqlCommand(sqlText, conn)
min = CDate(cmd1.ExecuteScalar())
If Not IsDate(min) Then
min = CType(CDate("01.01." & myyear) & " 00:00:00", Date)
End If
fromdate = CType(CDate(min), Date)
sqlText = "SELECT max(to_date(mydate, 'DD.MM.YYYY')) FROM " & mytable
cmd1 = New NpgsqlCommand(sqlText, conn)
max = CDate(cmd1.ExecuteScalar())
If Not IsDate(max) Then
max = CType(CDate("31.12." & myyear) & " 23:59:59.9999", Date)
End If
todate = CType(CDate(max), Date)
Try something like:
SELECT max(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY')),
min(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY'))
FROM table_name;
SELECT max(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY')),
min(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY'))
FROM table_name
WHERE date_part('year',to_date(nullif(mydatetxt,''), 'DD.MM.YYYY')) = 2012;