Get the Month and Year X number of months from now - flutter

I am attempting to generate a PageView that will display the Month and Year related to the number of times you swipe in either directon.
Example 1:
I swipe right twice, so I get Feb 2021
Example 2:
I swipe left 12 times, so I get April 2020
I have attempted to create a DateTime.now() and subtract an integer of months, but I'm not having much luck. I have looked at various plugins like DateUtils, but again no luck.
I have been at what should be a simple solution for while now and would appreciate a guidance.
The closet I get is the following which requires me to know the days in each month which isn't ideal
(DateTime.now().subtract(Duration(days: 90)).toString())

From DataTime docunamtion:
Returns a new [DateTime] instance with [duration] added to [this].
var today = DateTime.now();
var fiftyDaysFromNow = today.add(const Duration(days: 50));
// adds 1 days
DateTime _future = DateTime.now().add(const Duration(days: 1));
//substracts 1 day
DateTime _tomorrow2 = DateTime.now().subtract(const Duration(days: 1));
Also this, credit ,define the base time, let us say:
var date = new DateTime(2018, 1, 13);
Now, you want the new date:
var newDate = new DateTime(date.year, date.month - 1, date.day);
And you will get
2017-12-13

Y'all are going about it wrong. Presuming 24 hours in a day, or 30 days in a month, is just wrong. Here's how to always get midnight the first of the month, 7 months before today:
void main() {
var n = DateTime.now();
print(DateTime(n.year, n.month - 7, 1));
}
Just use DateTime constructors. They wrap around just fine. Works at month's end as well:
void main() {
var n = DateTime(2021, 2, 28);
print(DateTime(n.year, n.month, n.day + 1));
n = DateTime(2020, 2, 28);
print(DateTime(n.year, n.month, n.day + 1));
}
Which correctly shows 3/1 for 2021, and 2/29 for 2020, as it was a leap year.
Stop adding 24-hour days! I've got a video that explains why.... https://www.youtube.com/watch?v=usFSVUEadyo
And here's a video that goes into this with more detail: Proper Month and Day Arithmetic in Dart and Flutter: youtu.be/LpoBYgzKVwU

Related

How to get dates by days which have intervals of 7 days each

hello guyz am new to flutter and am practicing on dates then i encounter a difficulty on how can i acheive the result same below using a loop or something in order to get this result.
so far i tried is
final now = DateTime.now();
for(var d = 1 ; d <= 5 ; d++){
// Don't know whats next to do here to get the same result below
}
i want result like this
Apr 19, 2022
Apr 26, 2022
May 3, 2022
May 10, 2022
May 17, 2022
can some help me and explain.
Dart's DateTime class has an add function, where you can specify a duration which will be added the current Date.
Therefore, what you can do is:
DateTime now = DateTime.now();
for(var d = 1; d <= 5; d++) {
...
now = now.add(Duration(days: 7)); // here you can specify your interval. Also possible: hours, minutes, seconds, milliseconds and microseconds
}
I'll recommend reading the Docs, e.g. DateTime Docs and Duration Docs

Use the first day of the month as 1(integer)

I'm trying to build my first app using flutter framework. The app is about my "End of Year Challenge". It started from 1st Sept 2019 and will last till the end of this year.
What I'm trying to achieve is - I want to display the current day number of the challenge period. eg: 1st Sept is Day 1, 30th Sept is Day 30 and 1st Oct is Day 31 and so on.
I'm trying to get the first day of Sept and assign it to 1. Then using a loop I want the app to update the day to the current day. The loop will stop once the current day equals to 122 (as this would be the last day of the challenge)
Here's the screenshot of the UI
final firstSeptember = DateTime.utc(2019, DateTime.september, 1);
static const totalNumberOfDays = 122;
int noOfDay(){
int dayOne = firstSeptember.day; // I'm just trying codes, IDK the actual code/business logic
return dayOne;
}
In function you'd use
int noOfDay(){
var todayDate = DateTime.now();
final firstSeptember = DateTime.utc(2019, DateTime.september, 1);
var difference = todayDate.difference(firstSeptember);
return difference.inDays + 1;
}
Explanation:
Get today's date
var todayDate = DateTime.now();
You already have start date which is
final firstSeptember = DateTime.utc(2019, DateTime.september, 1);
All you need to do is subtraction.
var difference = todayDate.difference(firstSeptember);
int daysCompleted = difference.inDays + 1;

Dart/Flutter DateTime difference inDays error for March 31 April 1

I am trying to get the difference in Days between two dates picked from a DatePicker. This works fine except for ONE single date : March 31.
The difference in Days between two DateTimes is wrong by 1 day when one of the dates is March 31. I know this is due to Light Saving and March is 30.9… days long and not 31, hence I am guessing, the error. But does anyone know how to fix this other than manually checking if a date is equal to March 31 and adding one day to the result ?
Two very simple examples that can be run in the Dart Pad :
DateTime aprilFirst = DateTime(2019, 3, 30);
DateTime marchThirtyFirst = DateTime(2019, 3, 31);
print(aprilFirst.difference(marchThirtyFirst).inDays); => -1
DateTime marchThirty = DateTime(2019, 4, 1);
DateTime marchThirtyFirst = DateTime(2019, 3, 31);
print(marchThirty.difference(marchThirtyFirst).inDays); => 0
UPDATE:
DateTime aprilFirst = DateTime(2019, 4, 1);
print(aprilFirst.add(Duration(days: -1))); => 2019-03-30 23:00:00.000
This should print 2019-03-31 23:00:00.000 !
I tried Günter Zöchbauer's solution of making the DateTimes UTC but the results are the exact same:
DateTime aprilFirst = DateTime(2019, 4, 1).toUtc();
DateTime marchThirty = DateTime(2019, 3, 30).toUtc();
DateTime marchThirtyFirst = DateTime(2019, 3, 31).toUtc();
print(aprilFirst.difference(marchThirtyFirst).inHours); => 23
print(aprilFirst.difference(marchThirtyFirst).inDays); => 0
print(marchThirty.difference(marchThirtyFirst).inHours); => -24
print(aprilFirst.add(Duration(days: -1))); => 019-03-30 22:00:00.000Z
#Günter Zöchbauer put me on the right path. DateTime(...).toUTC() will fail for difference calculations. However, using the DateTime.utc(...) constructor does the trick !
DateTime aprilFirst = DateTime.utc(2019, 4, 1);
DateTime marchThirty = DateTime.utc(2019, 3, 30);
DateTime marchThirtyFirst = DateTime.utc(2019, 3, 31);
print(aprilFirst.difference(marchThirtyFirst).inHours); => 24
print(aprilFirst.difference(marchThirtyFirst).inDays); => 1
print(marchThirty.difference(marchThirtyFirst).inHours); => -24
print(aprilFirst.add(Duration(days: -1))); => 2019-03-31 00:00:00.000Z
Don't do Date comparison or operations with local dates. Convert it to UTC first. Otherwise daylight savings and other local DateTime related exceptions will cause all kinds of surprising effects.
DateTime aprilFirst = DateTime(2019, 3, 30).toUtc();
DateTime marchThirtyFirst = DateTime(2019, 3, 31).toUtc();
print(aprilFirst.difference(marchThirtyFirst).inDays); => -1
If the result is a DateTime you can convert it back using xxx.toLocal()
There is also a constructor that allows to create an UTC DateTime instead of creating a local DateTime and then converting to UTC.
Try this package, Jiffy uses the momentJs concept of date-time difference
You can see dicussion here https://github.com/moment/moment/pull/571
DateTime aprilFirst = DateTime(2019, 3, 30);
DateTime marchThirtyFirst = DateTime(2019, 3, 31);
Jiffy(aprilFirst).diff(marchThirtyFirst, Units.DAY); // -1
// or
Jiffy([2019, 3, 30]).diff([2019, 3, 31], Units.DAY); // -1
DateTime marchThirty = DateTime(2019, 4, 1);
DateTime marchThirtyFirst = DateTime(2019, 3, 31);
Jiffy(marchThirty).diff(marchThirtyFirst, Units.DAY); // 1
Jiffy(marchThirty).diff(marchThirtyFirst, Units.HOUR); // 24
Jiffy(marchThirty).diff(marchThirtyFirst, Units.MONTH); // 0
2021 Based on answer
extension DateCalcs on DateTime {
DateTime get dateOnlyUTC => DateTime.utc(this.year,this.month,this.day);
}
You've already figured out that you get an unexpected result due to your locale observing Daylight Saving Time. Duration internally stores a number of microseconds; Duration.days is measured in terms of 24-hour increments and not in terms of calendar days. From the DateTime documentation:
The difference between two dates in different time zones is just the number of nanoseconds between the two points in time. It doesn't take calendar days into account. That means that the difference between two midnights in local time may be less than 24 hours times the number of days between them, if there is a daylight saving change in between. If the difference above is calculated using Australian local time, the difference is 7415 days and 23 hours, which is only 7415 whole days as reported by inDays.
See https://stackoverflow.com/a/71198806/ for a more general version of Benjamin's answer that computes the difference in days between two dates, ignoring the time (and therefore also ignoring Daylight Saving adjustments and time zones).

Flutter: Find the number of days between two dates

I currently have a user's profile page that brings out their date of birth and other details. But I am planning to find the days before their birthday by calculating the difference between today's date and the date of birth obtained from the user.
User's Date of Birth
And this is today's date obtained by using the intl package.
Today's date
I/flutter ( 5557): 09-10-2018
The problem I am facing now is, How do I calculate the difference in days of these two dates?
Are there any specific formulas or packages that are available for me to check out?
You can use the difference method provide by DateTime class
//the birthday's date
final birthday = DateTime(1967, 10, 12);
final date2 = DateTime.now();
final difference = date2.difference(birthday).inDays;
UPDATE
Since many of you reported there is a bug with this solution and to avoid more mistakes, I'll add here the correct solution made by #MarcG, all the credits to him.
int daysBetween(DateTime from, DateTime to) {
from = DateTime(from.year, from.month, from.day);
to = DateTime(to.year, to.month, to.day);
return (to.difference(from).inHours / 24).round();
}
//the birthday's date
final birthday = DateTime(1967, 10, 12);
final date2 = DateTime.now();
final difference = daysBetween(birthday, date2);
This is the original answer with full explanation: https://stackoverflow.com/a/67679455/666221
The accepted answer is wrong. Don't use it.
This is correct:
int daysBetween(DateTime from, DateTime to) {
from = DateTime(from.year, from.month, from.day);
to = DateTime(to.year, to.month, to.day);
return (to.difference(from).inHours / 24).round();
}
Testing:
DateTime date1 = DateTime.parse("2020-01-09 23:00:00.299871");
DateTime date2 = DateTime.parse("2020-01-10 00:00:00.299871");
expect(daysBetween(date1, date2), 1); // Works!
Explanation why the accepted answer is wrong:
Just run this:
int daysBetween_wrong1(DateTime date1, DateTime date2) {
return date1.difference(date2).inDays;
}
DateTime date1 = DateTime.parse("2020-01-09 23:00:00.299871");
DateTime date2 = DateTime.parse("2020-01-10 00:00:00.299871");
// Should return 1, but returns 0.
expect(daysBetween_wrong1(date1, date2), 0);
Note: Because of daylight savings, you can have a 23 hours difference between some day and the next day, even if you normalize to 0:00. That's why the following is ALSO incorrect:
// Fails, for example, when date2 was moved 1 hour before because of daylight savings.
int daysBetween_wrong2(DateTime date1, DateTime date2) {
from = DateTime(date1.year, date1.month, date1.day);
to = DateTime(date2.year, date2.month, date2.day);
return date2.difference(date1).inDays;
}
Rant: If you ask me, Dart DateTime is very bad. It should at least have basic stuff like daysBetween and also timezone treatment etc.
Update: The package https://pub.dev/packages/time_machine claims to be a port of Noda Time. If that's the case, and it's ported correctly (I haven't tested it yet) then that's the Date/Time package you should probably use.
Use DateTime class to find out the difference between two dates.
DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11');
DateTime dateTimeNow = DateTime.now();
final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');
or
You can use jiffy. Jiffy is a date dart package inspired by momentjs for parsing, manipulating and formatting dates.
Example:
1. Relative Time
Jiffy("2011-10-31", "yyyy-MM-dd").fromNow(); // 8 years ago
Jiffy("2012-06-20").fromNow(); // 7 years ago
var jiffy1 = Jiffy()
..startOf(Units.DAY);
jiffy1.fromNow(); // 19 hours ago
var jiffy2 = Jiffy()
..endOf(Units.DAY);
jiffy2.fromNow(); // in 5 hours
var jiffy3 = Jiffy()
..startOf(Units.HOUR);
jiffy3.fromNow();
2. Date Manipulation:
var jiffy1 = Jiffy()
..add(duration: Duration(days: 1));
jiffy1.yMMMMd; // October 20, 2019
var jiffy2 = Jiffy()
..subtract(days: 1);
jiffy2.yMMMMd; // October 18, 2019
// You can chain methods by using Dart method cascading
var jiffy3 = Jiffy()
..add(hours: 3, days: 1)
..subtract(minutes: 30, months: 1);
jiffy3.yMMMMEEEEdjm; // Friday, September 20, 2019 9:50 PM
var jiffy4 = Jiffy()
..add(duration: Duration(days: 1, hours: 3))
..subtract(duration: Duration(minutes: 30));
jiffy4.format("dd/MM/yyy"); // 20/10/2019
// Months and year are added in respect to how many
// days there are in a months and if is a year is a leap year
Jiffy("2010/1/31", "yyyy-MM-dd"); // This is January 31
Jiffy([2010, 1, 31]).add(months: 1); // This is February 28
You can Use the Datetime class to find the difference between the two years without using intl to format the date.
DateTime dob = DateTime.parse('1967-10-12');
Duration dur = DateTime.now().difference(dob);
String differenceInYears = (dur.inDays/365).floor().toString();
return new Text(differenceInYears + ' years');
Naively subtracting one DateTime from another with DateTime.difference is subtly wrong. As explained by the DateTime documentation:
The difference between two dates in different time zones is just the number of nanoseconds between the two points in time. It doesn't take calendar days into account. That means that the difference between two midnights in local time may be less than 24 hours times the number of days between them, if there is a daylight saving change in between.
Instead of rounding the computed number of days, you can ignore Daylight Saving Time in DateTime calculations by using UTC DateTime objects1 because UTC does not observe DST.
Therefore, to compute the difference in days between two dates, ignoring the time (and also ignoring Daylight Saving adjustments and time zones), construct new UTC DateTime objects with the same dates and that use the same time of day:
/// Returns the number of calendar days between [later] and [earlier], ignoring
/// time of day.
///
/// Returns a positive number if [later] occurs after [earlier].
int differenceInCalendarDays(DateTime later, DateTime earlier) {
// Normalize [DateTime] objects to UTC and to discard time information.
later = DateTime.utc(later.year, later.month, later.day);
earlier = DateTime.utc(earlier.year, earlier.month, earlier.day);
return later.difference(earlier).inDays;
}
Update
I've added a calendarDaysTill extension method to package:basics that can do this.
1 Be aware that converting a local DateTime object to UTC with .toUtc() will not help; dateTime and dateTime.toUtc() both represent the same moment in time, so dateTime1.difference(dateTime2) and dateTime1.toUtc().difference(dateTime.toUtc()) would return the same Duration.
If anyone wants to find out the difference in form of seconds, minutes, hours, and days. Then here is my approach.
static String calculateTimeDifferenceBetween(
{#required DateTime startDate, #required DateTime endDate}) {
int seconds = endDate.difference(startDate).inSeconds;
if (seconds < 60)
return '$seconds second';
else if (seconds >= 60 && seconds < 3600)
return '${startDate.difference(endDate).inMinutes.abs()} minute';
else if (seconds >= 3600 && seconds < 86400)
return '${startDate.difference(endDate).inHours} hour';
else
return '${startDate.difference(endDate).inDays} day';
}
Beware of future "bugs" with selected answer
Something really missing in the selected answer - massively upvoted oddly - is that it will calculate the difference between two dates in term of:
Duration
It means that if there is less than 24h of differences both dates will be considered to be the same!! Often it is not the desired behavior. You can fix this by tweaking slightly the code in order to truncate from the day the clock:
Datetime from = DateTime(1987, 07, 11); // this one does not need to be converted, in this specific example, but we assume that the time was included in the datetime.
Datetime to = DateTime.now();
print(daysElapsedSince(from, to));
[...]
int daysElapsedSince(DateTime from, DateTime to) {
// get the difference in term of days, and not just a 24h difference
from = DateTime(from.year, from.month, from.day);
to = DateTime(to.year, to.month, to.day);
return to.difference(from).inDays;
}
You can hence detect if from was before to, as it will return a positive integer representing the difference in term of number of days, else negative, and 0 if both happened on same day.
It is indicated in the documentation what this function return and in many usecases it can lead to some problem that may be difficult to debug if following the original selected answer:
Returns a Duration with the difference when subtracting other (from) from this (to).
Hope it helps.
void main() {
DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-09-12 10:57:00");
Duration diff = dt1.difference(dt2);
print(diff.inDays);
//output (in days): 1198
print(diff.inHours);
//output (in hours): 28752
}
Simplest solution:
// d2.difference(d1).inDays
void main() {
final d1 = DateTime.now();
final d2 = d1.add(Duration(days: 2));
print(d2.difference(d1).inDays);
}
Check it out on DartPad example
Another and maybe more intuitive option is to use Basics package:
// the birthday's date
final birthday = DateTime(1967, 10, 12);
final today = DateTime.now();
final difference = (today - birthday).inDays;
For more information about the package: https://pub.dev/packages/basics
All of these answers miss a crucial part and that is leap year.
Here is the perfect solution for calculating age:
calculateAge(DateTime birthDate) {
DateTime currentDate = DateTime.now();
int age = currentDate.year - birthDate.year;
int month1 = currentDate.month;
int month2 = birthDate.month;
if (month2 > month1) {
age--;
} else if (month1 == month2) {
int day1 = currentDate.day;
int day2 = birthDate.day;
if (day2 > day1) {
age--;
}
}
return age;
}
The above answers are also correct, I just create a single method to find out the difference between the two days, accepted for the current day.
void differenceBetweenDays() {
final date1 = DateTime(2022, 01, 01); // 01 jan 2022
final date2 = DateTime(2022, 02, 01); // 01 feb 2022
final currentDay = DateTime.now(); // Current date
final differenceFormTwoDates = daysDifferenceBetween(date1, date2);
final differenceFormCurrent = daysDifferenceBetween(date1, currentDay);
print("difference From date1 and date 2 :- "+differenceFormTwoDates.toString()+" "+"Days");
print("difference From date1 and Today :- "+differenceFormCurrent.toString()+" "+"Days");
}
int daysDifferenceBetween(DateTime from, DateTime to) {
from = DateTime(from.year, from.month, from.day);
to = DateTime(to.year, to.month, to.day);
return (to.difference(from).inHours / 24).round();
}
var start_date = "${DateTime.now()}";
var fulldate =start_date.split(" ")[0].split("-");
var year1 = int.parse(fulldate[0]);
var mon1 = int.parse(fulldate[1]);
var day1 = int.parse(fulldate[2]);
var date1 = (DateTime(year1,mon1,day1).millisecondsSinceEpoch);
var date2 = DateTime(2021,05,2).millisecondsSinceEpoch;
var Difference_In_Time = date2 - date1;
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
print(Difference_In_Days); ```
Extension on DateTime
With an extension class you could:
int days = birthdate.daysSince;
Example extension class:
extension DateTimeExt on DateTime {
int get daysSince => this.difference(DateTime.now()).inDays;
}

Get Every Tuesday of the month with Coldfusion

I'm currently working with jquery FullCalendar plugin to create a specific calendar.
One of my tasks I have to work out is how to get any given specific day for the month.
I'm currently using Coldfusion 10 for the server side so I'm wondering is there any specific way of getting every instance of a Tuesday into an array of dates?
Ideally I would like to do this on the server side and populate the calendar plugin.
My issue is primarily trying to source every specific day of a calendar month.
Any advice greatly appreciated.
The firstXDayOfMonth() UDF on CFLlib allows you to find the first of a given day-of-week in a given month. From there you just need to loop from that date adding 7 each iteration until the month is no long the selected month.
theMonth = month(now());
startDate = firstXDayOfMonth(3, theMonth, year(now()));
tuesdays = [];
for (date=startDate; month(date) == theMonth; date +=7){
arrayAppend(tuesdays, dateAdd("s",0, date)); // this just converts date from a number back to a date
}
writeDump(tuesdays);
Update:
Actually the approach for that UDF on CFLib is terrible. Use this variation instead:
function firstXDayOfMonth(dayOfWeek,month,year){
var firstOfMonth = createDate(year, month,1);
var dowOfFirst = dayOfWeek(firstOfMonth);
var daysToAdd = (7 - (dowOfFirst - dayOfWeek)) MOD 7;
var dow = dateAdd("d", daysToAdd, firstOfMonth);
return dow;
}
I'll update the UDF on cflib a bit later: I need to write some decent unit tests for it first, and am a bit busy # the moment.
The Short Version:
At this time, there is not a function in CF that gets all the Tuesdays. But here's an easy way to do it:
// assuming a year and month are defined already
var firstDayOfMonth = createDate( year, month, 1 );
var targetDayOfWeek = 3; // Tuesday is 3 if Sunday is 1
var dayOfWeekArray = []; // This is the outcome.
// loop through each day of the month adding the target days to the array.
for( i = 1; i LTE daysInMonth( firstDayOfMonth ); i++){
var loopingDate = createDate( year, month, i );
if( dayOfWeek( loopingDate ) == targetDayOfWeek ){
ArrayAppend( dayOfWeekArray, loopingDate );
}
}
dayOfWeekArray is an array of every Tuesday of a month.
More Detail:
Your title and post seem to conflict as far as what you're looking for, so I'm going to stick with the title, since that's why I came here...
Here's what you can do to find all the Tuesdays in a month:
Create a date Object
Loop through the days in the target month using the date Object
If the current day is Tuesday, add it to an array
Boom, you got all the Tuesdays of a month in an array
Here's the code I used (cfscript):
// assuming a year and month are defined already
var firstDayOfMonth = createDate( year, month, 1 );
var dayOfWeekArray = [];
var targetDayOfWeek = 3; // Tuesday is 3 if Sunday is 1. Do a quick writeDump in the loop if you're not sure.
for( i = 1; i LTE daysInMonth( firstDayOfMonth ); i++){
var loopingDate = createDate( year, month, i );
if( dayOfWeek( loopingDate ) == targetDayOfWeek ){
ArrayAppend( dayOfWeekArray, datePart( "d", loopingDate );
// ArrayAppend( dayOfWeekArray, loopingDate ); - use this if you'd rather have the whole date object
}
}
This gives you dayOfWeekArray which will be the date of each Tuesday of a particular month. For instance, this month (Jan 2019) will be [1, 8, 15, 22, 29]. You can change this to be the entire date object if you want - that's what I did in the short version at the top.