Howto get the first day of the week by week number

Today I faced with small problem. I prepared a chart where data was split by weeks. It was very easy except one thing: display the first day of the week instead of week number. Here is a one way to do it (the main idea belongs to my co-worker Igor):
sub get_date_by_week {
my $week = shift || 1;
my $year = shift || (localtime)[5];
my $pattern = shift || '%d/%m';
my $t = timelocal(0, 0, 0, 1, 0, $year);
my $w = (localtime($t))[6];
$w = ($w - 2) % 7 + 1;
my $wc = $week * 7 - $w;
return strftime($pattern, localtime($t + $wc * 24 * 3600));
}

Don’t forget to add this in your script/module:
use Time::Local qw(timelocal);
use POSIX qw(strftime);

Note: this approach works correctly if the week starts from Monday!

Update: But today I found that PostgreSQL can trancate date by week and return the first day of the week:
SELECT date_trunc('week', TIMESTAMP '2006-06-01 10:38:40')::date
Result: 2006-05-29
So, now I can group by this date instead of week number!

Published by

Michael Stepanov

Site owner and admin :)

4 thoughts on “Howto get the first day of the week by week number”


  1. private static String getDateByWeekNumber(int year, int weekNo, String pattern) {
    Calendar cal = Calendar.getInstance();
    cal.set(YEAR, year);
    cal.set(WEEK_OF_YEAR, weekNo);
    return new SimpleDateFormat(pattern).format(cal.getTime());
    }

    A bit more flexible than Monday_of_Week($week, $year), because you can customise Calendar in any way, but more verbose too.

  2. Yes, you’re right. Basically, your method is the same as our :). But today I found that PostgreSQL can trancate date by week and return the first day of the week:

    SELECT date_trunc('week', TIMESTAMP '2006-06-01 10:38:40')::date

    Result: 2006-05-29

Leave a Reply

Your email address will not be published. Required fields are marked *