這裏是包含兩種類型的國產日期的一些舊代碼,只有年月日,沒有時間或時區,日期等
它顯示瞭如何解析字符串轉換爲使用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