Search code examples
kdbq-lang

How to get first day of year in KDB/Q?


I'm looking for efficient function to get the first day of year in Q. Like 2017.05.10 -> 2017.01.01 or 2016.08.19 -> 2016.01.01.

The next snippet works, but it is not efficient

{"D"$(string `year$x),".01.01"} .z.d

Solution

  • A common trick in this kind of calculations is to use the fact that unlike dates, months are very regular: each year has exactly 12 months. Thus to find the first day of the year, we first cast the date to the month type, then round it down to the multiple of 12 and cast back to the date type:

    q)f:"d"$12 xbar"m"$
    q)f .z.d
    2017.01.01
    

    or with the OP's dates:

    q)f 2017.05.10 2016.08.19
    2017.01.01 2016.01.01