How to calculate Current Calendar Week Number




Below are examples of getting current calendar week number in many languages, like: Java, PHP, Perl, SQL (Oracle, MySQL, MS SQL), Python, Ruby

Java

java.util.Calendar.getInstance().get(java.util.Calendar.WEEK_OF_YEAR);

Perl

my $weekNumber = POSIX::strftime("%V", gmtime time);

Replace time with other UNIX timestamps for other week numbers.

PHP

$weekNumber = date("W"); 

or date("W", epoch) for other week numbers. Remember to use capital 'W' not 'w'.

MySQL

SELECT WEEKOFYEAR(NOW())

Replace now() with other dates eg. SELECT WEEKOFYEAR('2008-02-20');
(You can also use the WEEK function with mode=3 select week(now(),3))

MS SQL

SELECT DATEPART( wk, GETDATE() )

iPhone/Mac

[NSString stringWithFormat:@"Week %d", 
				  [calendar ordinalityOfUnit:NSWeekCalendarUnit inUnit:NSYearCalendarUnit forDate:date]]; 

Python

import time
				week_number_as_string = time.strftime("%W")
				week_number = int(week_number_as_string) 
				

Ruby

week_number = Time.now.strftime("%U")
Replace Time.now with Time.local(year,month,day) for other dates.
Formats:
%U - Week number of the year, starting with the first Sunday as the first day of the first week (00..53)
%V - Week number of year according to ISO 8601 (01..53)
%W - Week number of the year, starting with the first Monday as the first day of the first week (00..53)

Microsoft Excel

=WEEKNUM(A1)-1
Week numbers can vary based on your locality settings (not ISO-8601!). See discussion below.

Unix/Linux

date +%W 




Please leave your comments