Home > Software Development > Howto get the first day of the week by week number

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!

Categories: Software Development Tags:
  1. May 23rd, 2006 at 22:49 | #1

    Date::Calc has:

    ($y, $m, $d) = Monday_of_Week($week, $year);

  2. May 24th, 2006 at 00:01 | #2

    99% of code already written :) You need to just a find it … I couldn’t do it ;)

  3. May 31st, 2006 at 00:53 | #3
    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.

  4. June 1st, 2006 at 12:26 | #4

    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
  1. No trackbacks yet.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes