how to add weeks,month, year to a date in flutter - flutter

I have a date string in flutter which i am trying to add week, month and year but not sure how to do it.
in android java, we can add weeks, month, year in the following way
Calendar cal = Calendar.getInstance();
cal.setTime('2019-09-04');
cal.add(Calendar.WEEK_OF_MONTH,1); // add one week
cal.add(Calendar.WEEK_OF_MONTH, 2 ); // add two weeks
cal.add(Calendar.MONTH, 1); // add # of month
cal.add(Calendar.MONTH, 3); // add 3 months
cal.add(Calendar.YEAR, 1); // add 1 year
however, i dont know how to add this in flutter. i know i can use duration but it only accept number of days cal.add(new Duration(days: 30));
if i use duration, then i need to figure out how many number of days in a month, week, or year and it is more math. with the above code in android java, adding weeks , months or year will be taken by android. is there a way for flutter to add weeks, months or year to a date?
for example: if i have 01/31/2019 and i want to add a month then new date should be 02/28/2019. if i want add a month to 02/28/2019 then output should be 03/31/2019
same goes for weeks and years. flutter should add a week to a date if specify or a year and so on. thanks in advance

You can find everything you need on this medium article:
Top 7 Date methods
Let's suppose you have '2019-09-04', in Dart you have:
var myDate = DateTime.parse("2019-09-04 20:18:04Z");
myDate.add(Duration(days: 10, hours: 5)));
then print it out:
print(myDate.toLocal());
EDIT:
because of your comment below, to add years or month do as follow:
var date = new DateTime(2019, 9, 4);
var newDate = new DateTime(date.year + 1, date.month + 2, date.day);
You can find similar answer here: Add/Substract months/years to date in dart?

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

How to get previous 5 days date from given date?

How to get previous 5 days date(30/11/2020) from given date?
How to get previous 5 months from given date?
Simply add a negative Duration:
DateTime nowFiveDaysAgo = DateTime.now().add(Duration(days: -5));

How do I Determine The Number Of Days In A Month from a particular date in angularjs 2?

I am using angularjs 2 and type script.
I want the number of days in a month from a particular date given by user.
How do I Determine that?
Please help. Thanks in Advance.
As pointed out by Evgeny Shmanev, this answer is incorrect. Please see the correct answer by Zvi Tarem
You don't need angular, you can call this function:
function daysRemainingInMonth(date) {
var year = date.getYear();
var month = date.getMonth();
return new Date(year, month, 0).getDate()
}
Edit: Updated now that I know you have the date
It may be a bit late, but the right answer is a follows:
In order to find the number of days in a month, you need to get the 'date' of the 0th day of the next month:
let daysInMonth = new Date(year, month + 1, 0).getDate();

How to create a specific date in Google Script

I have a spreadsheet that asks people to enter in a day of the month when we need to send out a bill. What I want to do is create a calendar event based on that. So, essentially what I need is an event that starts at the current month, day from the spreadsheet, and continues to a specified point in time.
var monthlyDate = row[6]; // Seventh column, monthly date of payment
var curDate = new Date();
var curMonth = curDate.getMonth();
var curYear = curDate.getYear();
curDate.setDate(curMonth, monthlyDate, curYear);
Logger.log("Day of month: %s", monthlyDate);
Logger.log("Current Date: %s", curDate);
Logger.log("Current Date: %s", Date());
What I'm seeing is that the monthly date is coming in as a float "6.0" for example, and no matter what I enter in for monthlyDate in the setDate line, it keeps setting the date to 10/9/15 (Today is 10/15/15). I've hard-coded that value to many different numbers, but for some reason it's just not working.
How can I create a date (in any format) that follows the scheme "Current Month / Day from Speadsheet / Current Year" ?
The getMonth() method returns a "zero-indexed" number. So, it returns the number 9 for the 10th month. setDate() doesn't set the date, it sets the "Day of the Month". The name of that method is misleading.
Documentation - setDate()
So, the last two parameters that you are using in setDate() are doing nothing. You are setting the day of the month to 9.
If you want to set multiple date parameters at the same time, you need to use the new Date() method:
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
The month parameter accept values from 0 to 11, 0 is Jan and 11 is Dec
Date Reference

Crystal Date Parameter for last year

I have tried using this formula with a date parameter. It works for the other 11 months but not the 12th month. Could some one please let me know what additional code I need to add to the formula.
If {?End Date} = 12/14/13
I want the formula to = 12/31/12
This is what I have been using to make it work for the other 11 months.
Date(year({?End Date})-1, month({?End Date})+1,1) - 1
I receive an error that the month needs to be 1 - 12.
Any suggestions will be greatly appreciated.
Thanks
This will give you the last day of the month of the previous year:
DateAdd("m", 1, DateTime( Year({immaster.timestmp})-1, Month({immaster.timestmp}), 1, 0,0,0 )) - 1
Try this.
CDate(Year(DateAdd ('yyyy',-1,CurrentDate)),Month(DateAdd ('M',0,CurrentDate)),31)