Flutter check last day in the month (List of datetime) - flutter

I have a List of different DateTime where for each month of the year there are from 7-15 days with an interval of a couple of days. For example: 01.07, 04.07, 09.07, 14.07, 20.07..., 04.08, 10.08 Question: How do I check if the date is the last for the given month? For example, the date 23.07 may be the last date for the month number 07. Thanks
I need to get a function to check. As input I get a DateTime which is augmented by a Bloc, so I need a check function.

Just add one to the date, and see if it's in the next month:
void main(List<String> arguments) {
for (final w
in '2022-01-01 2022-01-30 2022-01-31' ' 2022-02-01 2022-02-28 2024-02-28'
.split(' ')) {
// print(w);
final wd = DateTime.parse(w);
final isLastDay = isLastDayOfMonth(wd);
print('$w is last day of month? $isLastDay');
}
}
bool isLastDayOfMonth(DateTime when) {
return DateTime(when.year, when.month, when.day + 1).day == 1;
}
### output:
2022-01-01 is last day of month? false
2022-01-30 is last day of month? false
2022-01-31 is last day of month? true
2022-02-01 is last day of month? false
2022-02-28 is last day of month? true
2024-02-28 is last day of month? false

I would filter for the month, sort the list and take the first entry:
void main() {
List<DateTime> list = [DateTime(2000,06,23), DateTime(2000,06,21),DateTime(2000,06,22)];
list = list.where((date) => (date.month == 6)).toList();
list.sort((a,b) => b.day.compareTo(a.day));
print(list[0]);
}

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

Recurring for month and week in Flutter

I am trying to create a feature where I can transfer money by scheduling, so for that, I need a recurring option for the month and weak, And the problem that I face is, that if a user chooses the 31st of a month every month doesn't have the 31st, so the transaction should happen in that particular month's end date.
for example: If I start recurring date is 31st May 2022
no of transactions: 3
Current Output: Dates of transactions => 1st July 2022, 31st July 2022, 31st August 2022,
Correct Output: 30th June 2022, 31st July 2022, 31st August 2022,
Maybe something like I proposed here:
With lastDayOfMonth you could potentially do something like
extension AddMonth on DateTime {
DateTime addMonths([int amount = 1]) {
final plusXMonths = DateTime(year, month + amount, day);
final xMonthsAhead = DateTime(year, month + amount);
if (xMonthsAhead.lastDayOfMonth.compareTo(plusXMonths).isNegative) {
return xMonthsAhead.lastDayOfMonth;
} else {
return plusXMonths;
}
}
}
This proposition is based on this code that I created a PR for:
extension DateTimeLastFirstDay on DateTime {
/// Returns the Monday of this week
DateTime get firstDayOfWeek =>
isUtc ? DateTime.utc(year, month, day + 1 - weekday) : DateTime(year, month, day + 1 - weekday);
/// Returns the Sunday of this week
DateTime get lastDayOfWeek =>
isUtc ? DateTime.utc(year, month, day + 7 - weekday) : DateTime(year, month, day + 7 - weekday);
/// Returns the first day of this month
DateTime get firstDayOfMonth => isUtc ? DateTime.utc(year, month, 1) : DateTime(year, month, 1);
/// Returns the last day of this month (considers leap years)
DateTime get lastDayOfMonth => isUtc ? DateTime.utc(year, month + 1, 0) : DateTime(year, month + 1, 0);
/// Returns the first day of this year
DateTime get firstDayOfYear => isUtc ? DateTime.utc(year, 1, 1) : DateTime(year, 1, 1);
/// Returns the last day of this year
DateTime get lastDayOfYear => isUtc ? DateTime.utc(year, 12, 31) : DateTime(year, 12, 31);
}
Using the time package you could create a similar code for weeks.

How can I implement this type of week interval in flutter

I want to implement week interval feature where I can go on next by clicking on forward button.
First of all you can calculate the first and last day of the week by using this functions:
/// Find the first date of the week given a date.
/// ```
/// findFirstDateOfTheWeek(DateTime.now());
///```
DateTime findFirstDateOfTheWeek(DateTime dateTime) {
return dateTime.subtract(Duration(days: dateTime.weekday - 1));
}
/// Find last date of the week given a date.
///```
/// findLastDateOfTheWeek(DateTime.now());
///```
DateTime findLastDateOfTheWeek(DateTime dateTime) {
return dateTime.add(Duration(days: DateTime.daysPerWeek - dateTime.weekday));
}
Example:
DateTime now = DateTime.now();
DateTime fday = findFirstDateOfTheWeek(now );
DateTime lday = findLastDateOfTheWeek(now);
Once you got the first two values you can add 7 days to the date time passed to get the following week and so on:
DateTime.now().add(Duration(days: 7));
Hope it helps at least to get you started.

JMeter: How to get date of last week starting from sunday till saturday?

The scenario is I need to get last week date in format yyyy-mm-dd HH:mm:ss from last Sunday till Saturday(date will increment by 1 from last week of Sunday till Saturday) and like wise one more is to get date from past 20 weeks(till last week).
How may I get it?
Your requirement is not very clear so I can provide only a generic solution:
Getting the "last Sunday"
def calendar = Calendar.instance
def delta = Calendar.SUNDAY - calendar.get(Calendar.DAY_OF_WEEK)
calendar.add(Calendar.DAY_OF_WEEK, delta)
log.info('Last Sunday: ' + calendar.time.format("yyyy-MM-dd HH:mm:ss"))
Getting all previous "dates" for last 20 weeks:
def now = new Date()
use(groovy.time.TimeCategory) {
def twentyWeeksAgo = now - 30.weeks
def duration = now - twentyWeeksAgo
1.upto(duration.days, {
twentyWeeksAgo = twentyWeeksAgo + 1.days
log.info(twentyWeeksAgo.format('yyyy-MM-dd HH:mm:ss'))
})
}
More information:
Groovy TimeCategory
Creating and Testing Dates in JMeter - Learn How

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