What exactly does trunc(date, 'IW')?

Phate picture Phate · Sep 16, 2015 · Viewed 39.1k times · Source

For my project I need to have an absolute numerical correspondence between days of the week and 1...7 values.

As you probably know the association between days and numbers can vary according to the locale, for example in Germany Monday is 1 and Sunday is 7, while in US Monday is 2 while Sunday is 1.

So, searching for a solution, I found the following code which seems working regardless of the locale, assigning Monday=1...Sunday=7:

1 + TRUNC (date) - TRUNC (date, 'IW')

Can someone explain me how does it work? In particular I just can't understand what this instruction:

TRUNC (date, 'IW')

exactly does.

Answer

John picture John · Feb 21, 2017

TRUNC(DATE,'IW') returns the first day of the week. For me TRUNC(SYSDATE,'IW) returns Monday. Today is Tuesday Feb 21. Subtract from that TRUNC(SYSDATE,'IW') which would be Monday the 20th, and you'll get 1 (because 21-20=1). Add 1 onto that as you do in the beginning of your equation and you get 2, which we associate with Tuesday.