这里是包含两种类型的国产日期的一些旧代码,只有年月日,没有时间或时区,日期等
它显示了如何解析字符串转换为使用readDec
日期。请参阅parseDate
函数。用readDec
,读取这个数字,关于前导空格(因为filter
)或前导零并不重要,并且解析停在第一个非数字上。然后使用tail
(跳过非数字)到达日期的下一个数字字段。
它显示了输出格式的几种方式,但最灵活的方法是使用Text.printf
。见instance Show LtDate
。有了printf,任何事情都是可能的!
import Char
import Numeric
import Data.Time.Calendar
import Data.Time.Clock
import Text.Printf
-- ================================================================
-- LtDate
-- ================================================================
type Date=(Int,Int,Int)
data LtDate = LtDate
{ ltYear :: Int,
ltMonth:: Int,
ltDay :: Int
}
instance Show LtDate
where show d = printf "%4d-%02d-%02d" (ltYear d) (ltMonth d) (ltDay d)
toLtDate :: Date -> LtDate
toLtDate (y,m,d)= LtDate y m d
-- =============================================================
-- Date
-- =============================================================
-- | Parse a String mm/dd/yy into tuple (y,m,d)
-- accepted formats
--
-- @
-- 12\/01\/2004
-- 12\/ 1\' 4
-- 12-01-99
-- @
parseDate :: String -> Date
parseDate s = (y,m,d)
where [(m,rest) ] = readDec (filter (not . isSpace) s)
[(d,rest1)] = readDec (tail rest)
[(y, _) ] = parseDate' rest1
-- | parse the various year formats used by Quicken dates
parseDate':: String -> [(Int,String)]
parseDate' (y:ys) =
let [(iy,rest)] = readDec ys
year=case y of '\'' -> iy + 2000
_ ->
if iy < 1900 then iy + 1900 else iy
in [(year,rest)]
-- | Note some functions sort by this format
-- | So be careful when changing it.
showDate::(Int, Int, Int) -> String
showDate (y,m,d)= yy ++ '-':mm ++ '-':dd
where dd=zpad (show d)
mm = zpad (show m)
yy = show y
zpad [email protected](_:ds')
| ds'==[] = '0':ds
| otherwise = ds
-- | from LtDate to Date
fromLtDate :: LtDate -> Date
fromLtDate lt = (ltYear lt, ltMonth lt, ltDay lt)
一旦你有(Y,M,d),可以很容易地转换成一个Haskell库类型的数据操作。完成HS库之后,可以使用Text.printf
来格式化显示日期。
无论如何你不需要在%m,%d和%Y之间划线? – sclv 2010-11-14 19:42:44
@AlexBaranosky你可能要考虑接受这个问题的不同答案:) – Ben 2016-10-11 14:23:54