How to get a list of days or a number of days in a month with GWT? - 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.

Related

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;

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.

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

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