Data.Time.Calendar で前日、翌日、来月とか取得する

概要

  • 前日を取得したかったのでData.Time.Calendarを試した
  • ついでに今日とか翌日とか来月とか取得する方法など調べた

環境

Data.Time.Calendar

  • Data.Time.Calendar
  • 日付操作用のパッケージかな
  • stack install time
  • import Data.Time.Calendar

日付型を返す関数

  • Day 型の値が必要なので fromGregorian を使う
  • ありえない日付を入れた時、fromGregorian は最小最大を返すっぽい
  • fromGregorianValid でも良いです

fromGregorianで色々

> -- fromGregorianで色々
> fromGregorian 1900 10 12
1900-10-12
> fromGregorian 1900 0 12 -- これは1月になる
1900-01-12
> fromGregorian 1900 20 2 -- 12月
1900-12-02
> fromGregorian 1900 20 0 -- 12/1
1900-12-01
> fromGregorian 1900 10 0 -- 10/1
1900-10-01
> fromGregorian 1900 10 90 -- 10/31
1900-10-31
> fromGregorian 1900 11 90 -- 11/30
1900-11-30
> fromGregorian 1900 -1 10

<interactive>:29:1: error:
    • No instance for (Num (Int -> Int -> Day))
        arising from a use of-’
        (maybe you haven't applied a function to enough arguments?)
    • In the expression: fromGregorian 1900 - 1 10
      In an equation for ‘it’: it = fromGregorian 1900 - 1 10

<interactive>:29:21: error:
    • No instance for (Num (Integer -> Int -> Int -> Day))
        arising from the literal ‘1’
        (maybe you haven't applied a function to enough arguments?)
    • In the expression: 1
      In the second argument of ‘(-)’, namely ‘1 10’
      In the expression: fromGregorian 1900 - 1 10
> fromGregorian 1900 (-1) 10
1900-01-10

fromGregorianValidで色々

> -- fromGregorianValidで色々
> fromGregorianValid 1900 10 12 -- Just
Just 1900-10-12
> fromGregorianValid 1900 0 12 -- Nothingになる
Nothing
> fromGregorianValid 1900 20 2
Nothing
> fromGregorianValid 1900 20 0
Nothing
> fromGregorianValid 1900 10 0
Nothing
> fromGregorianValid 1900 10 90
Nothing
> fromGregorianValid 1900 11 90
Nothing
> fromGregorianValid 1900 -1 10

<interactive>:57:1: error:
    • No instance for (Num (Int -> Int -> Maybe Day))
        arising from a use of-’
        (maybe you haven't applied a function to enough arguments?)
    • In the expression: fromGregorianValid 1900 - 1 10
      In an equation for ‘it’: it = fromGregorianValid 1900 - 1 10

<interactive>:57:26: error:
    • No instance for (Num (Integer -> Int -> Int -> Maybe Day))
        arising from the literal ‘1’
        (maybe you haven't applied a function to enough arguments?)
    • In the expression: 1
      In the second argument of ‘(-)’, namely ‘1 10’
      In the expression: fromGregorianValid 1900 - 1 10
> fromGregorianValid 1900 (-1) 10
Nothing

前日を取得する方法

> day = fromGregorian 2018 11 01
> day
2018-11-01
> addDays 1 day
2018-11-02
> addDays 40 day
2018-12-11
> addDays (-1) day
2018-10-31
> addDays (-40) day
2018-09-22

todo

  • 今日 のとり方を調べる