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

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;

Related

Get the Month and Year X number of months from now

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

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.

Working with Dates in Google Apps Script

What I am trying to do here is this - I want to give index to only the workdays in each week.
So, if in a week, Monday and Wednesday are holidays, then Tuesday should get 1, Thursday should get 2, Friday should get the index 3. Otherwise, in a normal week without any holidays, Monday should get 1, Tuesday 2, Wednesday 3, and so on ...
Here is the code I have written (I haven't coded in years now, so please pardon the crude approach)
Sheet 'Holidays' contains a list of holidays in the column B starting from row 2
Variable date is the date for which I want to find out the index for
Variable dayOfTheWeek is the number of day of 'date' counted from last Sunday, so if date is a Monday, dayOfTheWeek is 1; if date is Tuesday, dayOfTheWeek is 2, and so on ...
function indexOfWorkdayOfTheWeek (date, dayOfTheWeek, lastSundayDate)
{
var activeSheet = SpreadsheetApp.getActiveSpreadsheet();
var activeCell = activeSheet.getActiveRange();
var activeRow = activeCell.getRowIndex();
var activeColumn = activeCell.getColumn();
var count = 1;
for (var j = 1; j < dayOfTheWeek; j++)
{
var date2 = lastSundayDate.valueOf() + j*86400;
Logger.log('Date ' + j + ' is:' + date2);
Logger.log('Last Sunday is:' + lastSundayDate);
if (holidayOrNot(date2) == true)
{
}
else
{
count = count + 1;
}
}
return count;
}
function holidayOrNot(date2)
{
var holidaysSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Holidays');
var listOfHolidays = holidaysSheet.getSheetValues(2, 2, 95, 1);
var isDateMatch = false;
for (var k = 0; k < 90; k++)
{
if (date2 == listOfHolidays[k].valueOf())
{
isDateMatch = true;
break;
}
else
{
continue;
}
}
return isDateMatch;
}
I think the problem is two-fold here:
The date2 calculation isn't working for some reason (var date2 = lastSundayDate.valueOf() + j*86400;)
The function holidayOrNot is returning false, no matter what, even if it encounters a holiday ... the condition date2 == listOfHolidays[k] isn't working for some reason...
Help would be appreciated!
maybe this method below could help you in your calculations, it returns an integer corresponding to the day of the year so if you apply this to your holidays days and compare to the days of interest it could be a good way to find matches.
here it is, just add these lines outside of any function in your script (so you can use it anywhere) then use it like this :
var d = new Date().getDOY();
Logger.log(d)
Here the method :
Date.prototype.getDOY = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
}
Assuming that lastSundayDate is being passed around correctly, I see a glaring problem:
lastSundayDate.valueOf().
valueOf() on Date objects returns the primitive value... it looks like you're going for adding a day to the date (86400 seconds * j)? I can't tell what the logic is supposed to be here. But the valueOf() date2 is definitely giving you an integer something like: 1384628769399 (see here).
What you really want to accomplish is something like Date.getDay(), or something similar so that you can add hours, days, etc. to the original Date. This is likely the source of all your problems.
What you can do is read the Mozilla Developer Network documentation on Date objects to see all of the functions on Dates and their uses. You can greatly simplify what you're trying to do by using these functions, instead of doing abstract operations like j * 86400.
It should also be noted that you can do simple operations such as the following, to add 4 hours to the current Date (time):
var myDate = new Date();
Logger.log(myDate); // ~ console.write
var laterDate = new Date(myDate.setHours(myDate.getHours() + 4));
Logger.log(laterDate); // ~ console.write
which gives the following:
[13-11-16 14:13:38:947 EST] Sat Nov 16 14:13:38 GMT-05:00 2013
[13-11-16 14:13:38:954 EST] Sat Nov 16 18:13:38 GMT-05:00 2013
Working with dates can be tricky - but it's always best to use the simplest methods that are available, which are built into the Date objects themselves. There are also numerous other libraries that provide extended functionality for Dates such as Date js.
If you're still running into your problem after attempting to try using methods I displayed above, please run your script and post both the Execution Transcript and the content of the Logger so that I can help you narrow down the issue :)

How to get a list of days or a number of days in a month with GWT?

What is counter part of this code in GWT ?
public int returnAllDaysOf(2012,6){
Calendar calendar = Calendar.getInstance();
calendar.set(2012, Calendar.FEBRUARY, 1);
int daysOfFeb = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
return daysOfFeb;
}
Thanks in advance for your help.
I want to get the number of days of a month in the client side. I searched Google and StackOverFlow but didn't get anything.
for example Feb has 29 days, Match has 31 days and so on ...
I don't know a direct way, but you can calculate this value by adding one month to your date, and then calcualting the difference in days:
final Date myDate = ...;
final Date copyOfDate = CalendarUtil.copyDate(myDate);
CalendarUtil.addMonthsToDate(copyOfDate, 1);
final int daysBetween = CalendarUtil.getDaysBetween(myDate, copyOfDate);
Note: This even works if myDate is something like 2012-01-31. copyOfDate is then 2012-03-02 (because february doesn't have 31 days), and the result is correct again.
"Cheating" way to do it:
int daysInCurrentMonth = new Date(year-1900, month+1, 0).getDate();
I.E.
int daysInJanuary2014 = new Date(114, 1, 0).getDate();
basically set the Date object to the 0th day of the NEXT month, then get the day of the month.
NOTE: Date(int year, int month, int date) expects year=calendarYear-1900 (i.e. 2014=114) and month is 0-based (i.e. January would be month 0)
and yes, I know this constructor is deprecated, but I still use it.
DateField dfMois = new DateField();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dfMois.getValue());
Date date = dfMois.getValue();
Date dateCopy = dateFin;
dateCopy.setDate(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
if(date.getMonth() == Calendar.FEBRUARY + 1){
date.setDate(31 - dateCopy.getDate());
date.setMonth(date.getMonth()-1);
}
else{
date.setDate(dateCopy.getDate());
}
dfMois.setValue(date);
In your code... it work.

Can this be done using LINQ/Lambda, C#3.0

Objective: Generate dates based on Week Numbers
Input: StartDate, WeekNumber
Output: List of dates from the Week number specified till the StartDate
i.e. If startdate is 23rd April, 2010 and the week number is 1, then the program should return the dates from 16th April, 2010 till the startddate.
The function
public List<DateTime> GetDates(DateTime startDate,int weeks)
{
List<DateTime> dt = new List<DateTime>();
int days = weeks * 7;
DateTime endDate = startDate.AddDays(-days);
TimeSpan ts = startDate.Subtract(endDate);
for (int i = 0; i <= ts.Days; i++)
{
DateTime dt1 = endDate.AddDays(i);
dt.Add(dt1);
}
return dt;
}
I am calling this function as
DateTime StartDate = DateTime.ParseExact("20100423", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
List<DateTime> dtList = GetDates(StartDate, 1);
The program is working fine.
Question is using C# 3.0 feature like Linq, Lambda etc. can I rewrite the program.
Why? Because I am learning linq and lambda and want to implement the same. But as of now the knowledge is not sufficient to do the same by myself.
Thanks.
Something like this:
public IEnumerable<DateTime> GetDates2(DateTime startDate, int weeks)
{
var days = weeks * 7;
return Enumerable.Range(-days, days + 1).Select(i => startDate.AddDays(i));
}
The Enumerable.Range method will return a sequence of integers within a specified range, in your example from -7 to 0.
After that I simply use each integer to substract that number of days from your initial startDate, building an IEnumerable<DateTime>.
You can try something like
int weeks = 1;
var days = from d in Enumerable.Range(-weeks * 7, weeks * 7 + 1)
select StartDate.AddDays(d);