在PureScript中获取第二天的日期

时间:2017-02-02 14:43:15

标签: date purescript

无论如何更优雅地编写以下功能?

我可以看到一些模式,但我不确定如何抽象它们或如何找到一种更简单的方法来编写函数。

type HasRemainder = Boolean

tomorrow :: Date -> Date
tomorrow date = unsafePartial $ canonicalDate y (fst m) (fst d)
  where d :: Tuple Day HasRemainder
        d = case toEnum $ 1 + fromEnum (day date) of
          Just v -> Tuple v false
          Nothing -> Tuple (unsafePartial $ fromJust $ toEnum 1) true
        m :: Tuple Month HasRemainder
        m = if snd d then
              case toEnum $ 1 + fromEnum (month date) of
                Just v -> Tuple v false
                Nothing -> Tuple (unsafePartial $ fromJust $ toEnum 1) true
            else Tuple (month date) false
        y :: Year
        y = if snd m then
              case toEnum $ 1 + fromEnum (year date) of
                Just v -> v
                -- use 2018 arbitrarly if the conversion from int to Date fails
                Nothing -> unsafePartial $ fromJust $ toEnum 2018
            else (year date)

2 个答案:

答案 0 :(得分:4)

我做这样的事情:

import Data.DateTime as DT
import Data.Maybe (maybe)
import Data.Time.Duration (Days(..))

tomorrow :: DT.Date -> DT.Date
tomorrow dt = maybe dt DT.date $ DT.adjust (Days 1.0) (DT.DateTime dt bottom)

虽然它会在给定日期为top的情况下返回输入日期(如果我没记错的话,这是275759的12月31日)。

adjustTime有一个DateTime功能,所以它只是Date缺少一个的疏忽。

答案 1 :(得分:0)

我会沿着这些方向尝试一些事情

getDatePart datepart defaultval1 defaultval2 = 
    case toEnum $ defaultval1 + fromEnum datepart of
    Just v -> Tuple v false
    Nothing -> Tuple (unsafePartial $ fromJust $ toEnum defaultval2) true

getDatePartDefault d datepart defaultval1 defaultval2 =
    if snd d then
        getDatePart datepart defaultval1 defaultval2
    else Tuple datepart false


 tomorrow :: Date -> Date
 tomorrow date = unsafePartial $ canonicalDate (fst y) (fst m) (fst d)
     where d :: Tuple Day HasRemainder
           d = getDatePart (day date) 1 1
           m :: Tuple Month HasRemainder
           m = getDatePartDefault d (month date) 1 1
           y :: Tuple Year HasRemainder
           y = getDatePartDefault d (year date) 1 2018

小心:未经测试

相关问题