How to calculate overlap week in Flex? - apache-flex

By using date object how we can calculate over lapping weeks?
For eg:
July 31(Tuesday) is end for the week number 38, However week number 38 ends Sunday i.e Aug 4.
However months are different
Any idea on this
Thanks all

In our Calendar component, we use this code to calculate the first date in a week; and I bet it could be modified to find the last Date of the Week. IT makes use of the DateUtils library
public static const DAY_OF_MONTH:String = "date";
/**
* This method gets the first date of the week which the given date is in.
*
* #param date This is the date for which we want to process.
* #param firstDayOfWeek The first day of the week, 0 (Sunday) - 6 (Saturday); 0 is the default. It will probably be used primarily for localization purposes.
*
* #return This returns a date representing the first day of the week.
*/
public static function firstDateOfWeek( date:Date, firstDayOfWeek : int = 0 ):Date {
var dayIncrement : int = dayOfWeekLocalized(date, firstDayOfWeek);
var returnDate : Date = DateUtils.dateAdd(DateUtils.DAY_OF_MONTH,-dayIncrement,date);
return returnDate;
}
/**
* This method returns the position of the day in a week, with respect to the firstDayOfWeek localization variable.
*
* If firstDayOfWeek is 0; then the week is display 0 (Sunday), 1 (Monday), 2 (Tuesday), 3 (Wednesday), 4 (Thursday), 5 (Friday), 6 (Saturday).
* So, a Sunday would return 0, a Saturday would return 6, and so on.
*
* If firstDayOfWeek is 1; then the week is displayed as 0 (Monday), 1 (Tuesday), 2 (Wednesday), 3 (Thursday), 4 (Friday), 5 (Saturday), 6 (Sunday).
* However, this situation will not change the date.day value. For display purposes we need a Sunday to return 6, a Saturday to return 5, and so on.
*
* This will presumably be used for display purposes.
*
* #param date This is the date to process.
* #param firstDayOfWeek The first day of the week, 0 (Sunday) - 6 (Saturday); 0 is the default. It will probably be used primarily for localization purposes.
*
* #return This returns a date representing the day’s location on the localized week display.
*/
public static function dayOfWeekLocalized( date:Date, firstDayOfWeek : int = 0 ):int {
var result : int = date.day - firstDayOfWeek;
if(result < 0){
result += 7;
}
return result;
}
To find the last date of a week, I suspect you can just call the firstDateOfWeek and add 6 days:
public static function lastDateOfWeek( date:Date, firstDayOfWeek : int = 0 ):Date {
var firstDateOfWeek : Date = firstDateOfWeek(date, firstDayOfWeek);
var returnDate : Date = DateUtils.dateAdd(DateUtils.DAY_OF_MONTH,6,firstDateOfWeek );
return returnDate;
}
Note: The second batch of code was written in a browser and is completely untested.
Update:
Given a specific date, you can find out the weekOfYear number using the weekOfYear method in the DateUtils library. Use the methods above to find the first and last date of the week in question
Conceptually like this:
var weekOfYear : Number = DateUtils.weekOfYear(myDate);
var firstDayOfWeek : Date = firstDateOfWeek(myDate);
var lastDayOfWeek : Date = lastDateOfWeek(myDate);

I dealt with this very question in this blog post. It's very simple, really. The last day of any given month is one day less than the first day of the next month. If the last day isn't a Saturday, you have an overlap.

Related

How to get start of or end of week in dart

How can I get the start of or end of a week in dart? An example is if three days ago was a Monday, and today is a Wednesday, how can I find the start of the week using dart, that is on Monday
You can get the weekday from the DateTime using https://api.dart.dev/stable/2.5.1/dart-core/DateTime/weekday.html and add/subtract this number from you date:
void main() {
final date = DateTime.parse('2019-10-08 15:43:03.887');
print('Date: $date');
print('Start of week: ${getDate(date.subtract(Duration(days: date.weekday - 1)))}');
print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - date.weekday)))}');
}
DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
UPDATE
Please read and upvote the answer from lrn. He knows a lot more about this stuff than me. :)
Dart DateTimes have a weekday getter which is 1 for Monday and 7 for Sunday. Using that, I would do:
DateTime mostRecentSunday(DateTime date) =>
DateTime(date.year, date.month, date.day - date.weekday % 7);
to get the most recent Sunday (which is the start of the current week if the week starts on a Sunday), and
DateTime mostRecentMonday(DateTime date) =>
DateTime(date.year, date.month, date.day - (date.weekday - 1));
for the most recent Monday (which is then the start of the current week if the week starts on a Monday).
You can generalize to
/// The [weekday] may be 0 for Sunday, 1 for Monday, etc. up to 7 for Sunday.
DateTime mostRecentWeekday(DateTime date, int weekday) =>
DateTime(date.year, date.month, date.day - (date.weekday - weekday) % 7);
If you are going to be using the results as calendar dates, I'd used DateTime.utc as the constructor instead. (Always use UTC for calendar dates, then you can do day-based arithmetic on them safely).
I'd even consider using DateTime.utc in any case because it avoids any potential issues with a daylight saving that starts at midnight (rare, but with time zones, even unlikely things tend to have happened somewhere at some point).
The way you do this will probably depend on what your app's localization is. If you want to treat Sunday as the start of the week, you would do this:
DateTime now = DateTime.now();
int currentDay = now.weekday;
DateTime firstDayOfWeek = now.subtract(Duration(days: currentDay));
If you are treating Monday as the start, then do this:
DateTime now = DateTime.now();
int currentDay = now.weekday;
DateTime firstDayOfWeek = now.subtract(Duration(days: currentDay - 1));
MaterialLocalizations
If you're using Dart in Flutter, you can use the MaterialLocalizations class to get the index of the first day of the week (0 = Sunday, 6 = Saturday). This should help you decide which method from above that you should use.
The example given for the firstDayOfWeekIndex property is a good reference:
var localizations = MaterialLocalizations.of(context);
// The name of the first day of week for the current locale.
var firstDayOfWeek = localizations.narrowWeekdays[localizations.firstDayOfWeekIndex];
The MaterialLocalizations class comes with a ton of built in methods to format and display DateTimes.
dateTime: 2021-01-26 11:21:05.429320
formatFullDate: Tuesday, January 26, 2021
formatCompactDate: 01/26/2021
formatMediumDate: Tue, Jan 26
formatShortDate: Jan 26, 2021
formatShortMonthDay: Jan 26
formatMonthYear: January 2021
formatYear: 2021
If none of these fit your needs, you can also use the DateFormat class to specify how the DateTime should be displayed. It's important to note that the DateFormat class indexes days differently where 1 = Monday and 7 = Sunday.
DateFormat.yMMMd().format(new DateTime.now()) // Jan 26, 2021
DateFormat(DateFormat.ABBR_MONTH_DAY).format(now) // Jan 26
DateFormat(DateFormat.WEEKDAY).format(now) // Tuesday
FIRST DAY OF THE WEEK
DateTime findFirstDateOfTheWeek(DateTime dateTime) {
return dateTime.subtract(Duration(days: dateTime.weekday - 1));
}
LAST DAY OF THE WEEK
DateTime findLastDateOfTheWeek(DateTime dateTime) {
return dateTime
.add(Duration(days: DateTime.daysPerWeek - dateTime.weekday));
}
LAST DAY OF THE MONTH
DateTime findLastDateOfTheMonth(DateTime dateTime) {
return DateTime(dateTime.year, dateTime.month + 1, 0);
}
FIRST DAY OF THE MONTH
DateTime findFirstDateOfTheMonth(DateTime dateTime) {
return DateTime(dateTime.year, dateTime.month, 1);
}
LAST DAY OF THE YEAR
DateTime findLastDateOfTheYear(DateTime dateTime) {
return DateTime(dateTime.year, 12, 31);
}
FIRST DAY OF THE YEAR
DateTime findFirstDateOfTheYear(DateTime dateTime) {
return DateTime(dateTime.year, 1, 1); }
Dart/Flutter – How to find the first date and the last date of a week
1. Find the first date of the week
/// Find the first date of the week which contains the provided date.
DateTime findFirstDateOfTheWeek(DateTime dateTime) {
return dateTime.subtract(Duration(days: dateTime.weekday - 1));
}
2. Find the last date of the week
/// Find last date of the week which contains provided date.
DateTime findLastDateOfTheWeek(DateTime dateTime) {
return dateTime.add(Duration(days: DateTime.daysPerWeek - dateTime.weekday));
}
Testing
void main() {
// Find first date and last date of THIS WEEK
DateTime today = DateTime.now();
print(findFirstDateOfTheWeek(today));
print(findLastDateOfTheWeek(today));
// Find first date and last date of any provided date
DateTime date = DateTime.parse('2020-11-24');
print(findFirstDateOfTheWeek(date));
print(findLastDateOfTheWeek(date));
}
// Output
2020-11-23 06:54:42.865446
2020-11-29 06:54:42.865446
2020-11-23 00:00:00.000
2020-11-29 00:00:00.000
None of the above worked for me but #JoeMuller gave an interesting piece of info on the material localizations, which led me to find out that for what i want, sunday in date.weekday should be 0 took a while to figure it out many thanks to joe and #julemand101 I have this for UK calendar starting from sunday and ending on saturday
void main() {
final date = DateTime.parse('2021-08-01');
print('Date: $date');
final weekDay = date.weekday == 7 ? 0 : date.weekday;
print('Start of week: ${getDate(date.subtract(Duration(days: weekDay)))}');
print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - weekDay - 1)))}');
}
DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
I have 2 function:
DateTime getStartTimeWeek([DateTime? date]) {
final currentDate = date ?? DateTime.now();
final dateTime = DateTime(currentDate.year, currentDate.month, currentDate.day);
return dateTime.subtract(Duration(days: currentDate.weekday - 1));
}
DateTime getEndTimeWeek([DateTime? date]) {
final currentDate = date ?? DateTime.now();
final dateTime = DateTime(currentDate.year, currentDate.month, currentDate.day, 23, 59, 59, 999);
return dateTime.add(Duration(days: DateTime.daysPerWeek - currentDate.weekday));
}
Below is the code which should work fine in most cases.
We can get start and end of the week like this:-
To get the first day of the week for a date use the below function.
Like Sunday (Also known as 7 in WeekDay).
Read lines of comments in code for code clarifications.
DateTime getFirstDayOfWeek({required DateTime currentDateTime}) {
// Converting date provided to UTC
// So that all things like DST don't affect subtraction and addition on date
DateTime dateTimeInUTC = DateTime.utc(
currentDateTime.year, currentDateTime.month, currentDateTime.day);
// Getting weekday for the date
// For reference Sunday weekday is 7 and Friday weekday is 5
int currentWeekDayInUTC = dateTimeInUTC.weekday;
// Getting Date for nearest Sunday from the provided date
// By going back a number of weekdays from the current date to reach Sunday
DateTime firstDayOfWeekInUTC;
// If current date is not Sunday subtract days to reach Sunday
if (currentWeekDayInUTC != DateTime.sunday) {
firstDayOfWeekInUTC =
dateTimeInUTC.subtract(Duration(days: currentWeekDayInUTC));
}
// If current date is Sunday use it as the first day of week
else {
firstDayOfWeekInUTC = dateTimeInUTC;
}
// Converting back the date for Sunday from UTC type to Local
// You can also use UTC type depending on your use case
DateTime firstDayOfWeekInLocal = DateTime(firstDayOfWeekInUTC.year,
firstDayOfWeekInUTC.month, firstDayOfWeekInUTC.day);
if (currentDateTime.isUtc) {
return firstDayOfWeekInUTC;
} else {
return firstDayOfWeekInLocal;
}
}
To get the last day of the week for a date use the below function.
Like Saturday (Also known as 6 in WeekDay).
Read lines of comments in code for code clarifications.
DateTime getLastDayOfWeek({required DateTime currentDateTime}) {
// Converting date provided to UTC
// So that all things like DST don't affect subtraction and addition on date
DateTime dateTimeInUTC = DateTime.utc(
currentDateTime.year, currentDateTime.month, currentDateTime.day);
// Getting weekday for the date
// For reference Sunday weekday is 7 and Friday weekday is 5
int currentWeekDayInUTC = dateTimeInUTC.weekday;
// Getting Date for nearest Saturday from the provided date
// By going forward a number of weekdays from the current date to reach Saturday
DateTime lastDayOfWeekInUTC;
// If current date is not Sunday add days enough to reach Saturday
if (currentWeekDayInUTC != DateTime.sunday) {
lastDayOfWeekInUTC = dateTimeInUTC
.add(Duration(days: DateTime.saturday - currentWeekDayInUTC));
}
// If current date is Sunday add days UpTo saturday
else {
lastDayOfWeekInUTC = dateTimeInUTC.add(Duration(days: DateTime.saturday));
}
// Converting back the date for Sunday from UTC type to Local
// You can also use UTC type depending on your use case
DateTime lastDayOfWeekInLocal = DateTime(lastDayOfWeekInUTC.year,
lastDayOfWeekInUTC.month, lastDayOfWeekInUTC.day);
if (currentDateTime.isUtc) {
return lastDayOfWeekInUTC;
} else {
return lastDayOfWeekInLocal;
}
}

Find the number of week rows in a month

Given the start day (Wednesday = 4), and the number of days in a month (31), what is an elegant way to find the number of week rows a calendar of the month would require?
For the current month (startDay = 4, daysInMonth = 31), it would be 5. But if daysInMonth = 33, it would be 6 rows.
This doesn't quite work:
int numRows = (startDay+daysInMonth)/daysInWeek;
if ((startDay+daysInMonth) % daysInWeek != 0) {
numRows++;
}
Just change to
int numRows = (startDay + daysInMonth - 1) / daysInWeek;
if ((startDay+daysInMonth - 1) % daysInWeek != 0) {
numRows++;
}
and you should get the correct result.
EDIT: just to slightly expand on it : you have the right idea, you just forgot to account for the fact that the offset for day 1 is 0, not 1.
Actually, I think your original algorithm is correct, just need to subtract 1 when doing modulo daysInWeek.
daysInWeek = 7
startDay = 3 # Zero based day of week array, 3 = Wednesday
daysInMonth = 31
numRows = (startDay+daysInMonth)/daysInWeek
if ((startDay+daysInMonth - 1) % daysInWeek != 0)
numRows += 1
end
print numRows
It shows 6 correctly. (BTW, why do you need a month with 33 days?) It should be 6 rows for a 33 day month (if there was such a thing).
int temp = daysInMonth;
temp = temp - (7 - startDay);
int result = ceiling(temp / 7) + 1;
Here is a generic way to do it in C#, which works by counting the Saturdays in a month and then adding one if there's any left over days. Since it literally reads a calendar like a human would, there's no strange calendar arithmetic needed. It's all offloaded to the C# DateTime code, we just piggyback off that.
I chose Saturday because most calendars go Sunday (far left) to Saturday (far right). You can just choose a different day if you wish to denote the end of a week.
public static int RowsForMonth(int year, int month)
{
int days = DateTime.DaysInMonth(year, month);
int rows = 0;
int i = 0;
while(i < days)
{
i++;
DateTime date = new DateTime(year, month, i);
if (date.DayOfWeek == DayOfWeek.Saturday || i == days)
rows++;
}
return rows;
}
Jan 2022 -> 6
Feb 2022 -> 5
Mar 2022 -> 5

Given a date how to get Sunday & Saturday of that week

I want to get the Sunday & Saturday of the week from which a date is provided.
I have access to the following functions only:
getDate() returns a number from 0-6 (0 being sunday)
getDay() returns a number from 1-31
getMonth() returns a number from 0-11
getFullYear() returns the current year
I am doing this on titanium.
Per your description above, I came up with:
var sat = new Date(input.getFullYear(), input.getMonth(), 6 - input.getDate() + getDay());
var sun = new Date(input.getFullYear(), input.getMonth(), getDay() + (input.getDate() - 6));
If I follow the MDN doc, I come up with (works in Ti too):
var sat = new Date(input.getFullYear(), input.getMonth(), 6 - input.getDay() + input.getDate());
var sun = new Date(input.getFullYear(), input.getMonth(), input.getDate() + (input.getDay() - 6));
Where input is a javascript Date object.
The date object will take care or changing the month and/or year if necessary.
Hope this helps.

comparison of two dates

how to compare values of 2 dates using actionscript
i executed this code in my program..
var time1:Date = new Date(Number(fromDate.substr(0,4)),Number(fromDate.substring(5,7))-1, Number(fromDate.substring(8,10)));
var time2:Date = new Date(Number(toDate.substr(0,4)),Number(toDate.substring(5,7))-1, Number(toDate.substring(8,10)));
if(time1.getTime() > time2.getTime())
{
Alert.show(time1 + ” is after ” + time2);
}
im getting error: Error: Unexpected end of token stream
AS3 doesn't support a time delta class like Python so this can actually be a little tricky. There are lots of things to be worried about when comparing dates:
daylight savings time (when the clocks change one hour in certain countries Spring and Fall)
time-zones
leap-years
The roughest way to do things is just to use the time property of a date object. This way you can get an accurate difference between two dates expressed in milliseconds:
var date1:Date = new Date(2001, 9, 12); // Oct. 12, 2001
var date2:Date = new Date(2010, 5, 22); // Jun. 22, 2010
var differenceInMilliseconds:Number = date2.time - date1.time;
Using this time property you can do things like check if one date is before or after another date. You can also do rough calculations on the distance between two dates by defining some constants:
const MILLISECOND_PER_SECOND:int = 1000;
const SECOND_PER_MINUTES:int = 60;
const MINUTES_PER_HOUR:int = 60;
const HOURS_PER_DAY:int = 24;
// ... etc ...
var differenceInSeconds:Number = differenceInMilliseconds / MILLISECOND_PER_SECOND;
var differenceInMinutes:Number = differenceInSeconds / SECOND_PER_MINUTES;
var differenceInHouse:Number = differenceInMinutes / MINUTES_PER_HOUR;
var differenceInDays:Number = differenceInHouse / HOURS_PER_DAY;
Once you get to the level of days you could get problems with daylight savings time since the change of 1 hour can make it seem like a full day has passed when it really hasn't. After days and into weeks or months you run into leap year problems.
Assuming your string processing code correctly gives you valid date objects, just use the ObjectUtil.dateCompare function to compare 2 dates:
http://livedocs.adobe.com/flex/3/langref/mx/utils/ObjectUtil.html#dateCompare%28%29
if( ObjectUtil.dateCompare(date1, date2) == 1 ){}
I'm pretty sure that the return types defined in the ASDocs are wrong.
It'll actually return -1 if a is null or before b; 1 if b is null or before.
If you have two dates as Date objects already, just compare them. e.g. a.getTime() > b.getTime().
If they are strings, see their format is acceptable by the default Date.parse() function. If not, you may have other work to do.
Let's see your values first, shall we?
private function differenceBetweenDates(date1:Date, date2:Date):Number{
var MS_PER_DAY:uint = 1000 * 60 * 60 * 24;
var tempDate:Date = new Date(date2.time - date1.time);
var difference:Number =
Math.abs(Math.round((tempDate.time / MS_PER_DAY)));
return difference;
}
I have achieved comparing dates succesfully using below code:
//here i have to compare two dates ,these are startdate and enddate.
// gets millisecs counts from 1970 midnight till sellected start date
var Starttimecounts : Number = popJobWin.DFStartDate.selectedDate.time;
// gets millisecs counts from 1970 midnight till sellected end date
var Endtimecounts : Number = popJobWin.DFEndDate.selectedDate.time ;
if (Starttimecounts > Endtimecounts)
{
Alert.show('end date should not lesser than start date..wrong!');
//replace your logic here
}
else
{
Alert.show('correct!');
//replace your logic here
}

retrievind date in asp.net

I need to retrieve the current date in asp.net and then compare that with the date given by the user in textbox1.text(mm/dd/yyyy format), if date date given is greater than current date then error else add 4months2days with that date and display it in textbox2.text.
help me please,
thanking you guys,
Indranil
DateTime dateToCompare;
if(DateTime.TryParse(textbox1.text, out dateToCompare))
{
DateTime current = DateTime.Now;
TimeSpan ts = current - dateToCompare;
if (ts.Ticks < 0)
{
//display error
}
else
textbox2.text = dateToCompare.AddMonths(4).AddDays(2).ToString("mm/dd/yyyy");
}
}
I'm not going to write your code, but in .NET you can use ToString to specify a date format, TryParse to get a date out of a string. And AddDays, AddMonths etc to manipulate a date.
In javascript, there's no simple way to format output, but you can use getMonth etc to prompt the individual values and concatenate a string from that. You can use a combination of getDate and setDate to manipulate dates. It automatically corrects for new months, i.e. if you run myDate.setDate( myDate.getDate() + 60 ) it'll actually increment by 60 days; you won't end up with a weird date like May 74th.
Keep in mind that months in javascript are zero-based, ie January is 0, February is 1, etc.
You can create a new date in javascript by new Date(yy, mm, dd) or new Date('yy/mm/dd'), so you could string-manipulate an input and create a date from that.
To compare two dates, you can subtract one from the other, and get the difference in milliseconds.
if ( dateA - dateB < 0 ) // dateB is greater than dateA (occurrs later)
and
var diff = Math.abs(dateA - dateB) // difference in ms, no matter which date is greater
DateTime date1 = new DateTime();
if(DateTime.TryParse(textbox1.text, out date1)){
if (date1.CompareTo(DateTime.Now) > 0)
{
//Error code here
}else
{
textbox2.text = date1.AddMonths(4).AddDays(2);
}
}

Resources