Avg. Rating 5.0

Problem

Recently, working on a project, i needed to get the working days (monday to friday) from the current week. I needed it to compare the resulting array against a json object. Since there is no direct function in the Date class, i figured out a simple way to get the wanted result.

Solution

The key here is to get the current day, and get it back to the last sunday. When this is done, a simple iteration increments this date until friday.

Detailed explanation

There is in the current Date class in ActionScript 3 no way to parse through a week number and get all the working days contained in that week. So you would have to create this function yourself. I bumped into that problem a few days ago, and i thought it would be good to share the solution with you.

 

Begin by declaring some variables.

var currentWeekDays:Array = new Array();
var date:Date = new Date();
var formattedDate:String;


Change the date back to the last sunday, you can do that by substracting the day's index to the date.

date.setDate(date.getDate() - date.getDay());


Now, create a loop that will iterate the date 5 times (from monday to friday). If you need the complete week, iterate 7 times. In my case, i needed to format the result to "YYYY-MM-DD", so i will add some operations.

for ( var i:int = 0; i < 5; i++ ) {
  date.setDate(date.getDate() + 1);
  formattedDate = date.getFullYear().toString();
  formattedDate += "-";
  formattedDate += (date.getMonth() + 1< 10) ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  formattedDate += "-";
  formattedDate += (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate().toString();
  currentWeekDays.push(formattedDate);
}


And here you have an Array containing the current week days. Hope you'll find that code useful.

 

If you want the full code in one simple function, here it is :

private function getCurrentWeekDays():Array
{
  var output:Array = new Array(); var date:Date = new Date();
  var formattedDate:String;
  
  date.setDate(date.getDate() - date.getDay());
  
  for ( var i:int = 0; i < 5; i++ ) {
    date.setDate(date.getDate() + 1);
    
    formattedDate = date.getFullYear().toString();
    formattedDate += "-";
    formattedDate += (date.getMonth() + 1 < 10) ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
    formattedDate += "-";
    formattedDate += (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate().toString();
    
    output.push(date);
  }
  
  return output;
}

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes