Flex, how to get the week of the year for a date?

I could not find the method in the Flex Date object to get the week of the year (1 to 52)

What is the best way to find this? Is there a useful library for flex for date operations like JodaTime in Java.

+4
source share
4 answers

I do not know about the library, but this function will give you the index of the week (based on zero).

function getWeek(date:Date):Number { var days:Array = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; var year:Number = date.fullYearUTC; var isLeap:Boolean = (year % 4 == 0) && (year % 100 != 0) || (year % 100 == 0) && (year % 400 == 0); if(isLeap) days[1]++; var d = 0; //month is conveniently 0 indexed. for(var i = 0; i < date.month; i++) d += days[i]; d += date.dateUTC; var temp:Date = new Date(year, 0, 1); var jan1:Number = temp.dayUTC; /** * If Jan 1st is a Friday (as in 2010), does Mon, 4th Jan * fall in the first week or the second one? * * Comment the next line to make it in first week * This will effectively make the week start on Friday * or whatever day Jan 1st of that year is. **/ d += jan1; return int(d / 7); } 
+5
source

I just want to point out that there is an error in the above solution.

 for(var i = 0; i < date.month; i++) 

it should be

 for(var i = 0; i < date.monthUTC; i++) 

for proper operation.

Nevertheless, thanks for the solution, it helped me a lot :)

+1
source

Before d is divisible by 7, it must be reduced by 1. Otherwise, Saturday will go to the next week.

Take 2011 as an example; 1/1/2011 is Saturday. This should be week at 0, and 1/8/2011 should be at week 1.

If d is not decremented, then 1 + 6 = 7/7 = 1, and 8 + 6 = 14/7 = 2. Therefore, they are incorrect.

+1
source

I tried using the Amarghosh function, but I had problems with the UTC values. And from the first days of the year.

So I changed the setting of jan1 (depending on Sunday) and the calculation for the last week

Here is the function I'm using based on Amarghosh one:

 public static function getWeek(date:Date):String { var days:Array = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; var year:Number = date.fullYear; var isLeap:Boolean = (year % 4 == 0) && (year % 100 != 0) || (year % 100 == 0) && (year % 400 == 0); if(isLeap) days[1]++; var d:Number = 0; for(var i:int = 0; i < (date.month); i++){ d += days[i]; } d += date.date; var temp:Date = new Date(year, 0, 1); var jan1:Number = temp.day; if(jan1 == 0) // sunday jan1 = 7; d += jan1 - 1; var week:int = int((d-1) / 7); if(week == 0) // les premiers jours de l'annΓ©e week = 52; return (week < 10 ? "0" : "") + week; } 
+1
source

Source: https://habr.com/ru/post/1302860/


All Articles