打印当月的日历

时间:2018-03-17 17:27:22

标签: sqlite

看来我的练习没有任何实际用法,但我想知道我的问题在哪里。我试图打印当月的日历(从星期一开始),所以我接下来解决这个问题的愿景。首先,它需要获得该月的总天数。

 WITH days(total) AS (
    SELECT 1
    UNION ALL
    SELECT total + 1 FROM days
    LIMIT (
       SELECT CAST(
          julianday('now', 'start of month', '+1 month') -
          julianday('now', 'start of month') AS INTEGER
       )
    )
 ) SELECT group_concat(total) FROM days;

其次,如果月份的第一天不是星期一,则需要N个空格。

 WITH days(total) AS (
    WITH spaces(nil) AS (
       SELECT CHAR(32)
       UNION ALL
       SELECT nil FROM spaces
       LIMIT (
          SELECT strftime('%w', julianday('now', 'start of month')) -1
       )
    ) SELECT group_concat(nil) || 1 FROM spaces
    UNION ALL
    SELECT total + 1 FROM days
    LIMIT (
       SELECT CAST(
          julianday('now', 'start of month', '+1 month') -
          julianday('now', 'start of month') AS INTEGER
       )
    )
 ) SELECT group_concat(total) FROM days;

第三,这是两个问题:一个月的最后一天迷路了,以及如何分割相同块的序列?也许有更好的解决方案?

1 个答案:

答案 0 :(得分:0)

找到解决方案here

WITH seg(b, s) AS ( -- split string on segments
   VALUES (1, '')
   UNION ALL
   SELECT b + 21, SUBSTR((
      WITH nil(e) AS ( -- spaces (if not a Monday)
         SELECT CHAR(32)
         UNION ALL
         SELECT e FROM nil
         LIMIT (
            SELECT ( -- Sunday is presented by zero, so fix this
               CASE WHEN dow = CAST(0 AS INTEGER) THEN 7 ELSE dow END
            ) FROM ( -- day of week
               SELECT strftime('%w', julianday('now', 'start of month')) AS dow
            )
         )
      ) SELECT replace( -- replace all commas on spaces
         'Mo,Tu,We,Th,Fr,Sa,Su,' || rtrim(group_concat(printf('%2s', e))) || (
            WITH seq(n) AS ( -- days sequence
               SELECT 1
               UNION ALL
               SELECT n + 1 FROM seq
               LIMIT (
                  SELECT CAST(
                     julianday('now', 'start of month', '+1 month') -
                     julianday('now', 'start of month') AS INTEGER
                  )
               )
            ) SELECT group_concat(printf('%2s', n)) FROM seq
      ), ',', CHAR(32)) FROM nil
   ), b, 21) FROM seg
   LIMIT 8
) SELECT s FROM seg;