Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell function to get part of date as string

I have a beginner question about dates and String in Haskell.

I need to get part of date (year, month or day) as String in Haskell. I found out, that if I write the following two lines in GHCi

Prelude> now <- getCurrentTime
Prelude> let mon = formatTime defaultTimeLocale "%B" now

then mon is of type String. However, I am unable to put this in a function. I tried for instance the following:

getCurrMonth = do
    now <- getCurrentTime
    putStrLn (formatTime defaultTimeLocale "%B" now)

But this returns type IO () and I need String (also not IO String, only String).

I understand that do statement creates a monad, which I don't want, but I have been unable to find any other solution for getting date in Haskell.

So, is there any way to write a function like this?

Thanks in advance for any help!

like image 466
robodasha Avatar asked Apr 06 '11 22:04

robodasha


2 Answers

If you want to return a String representing the current time, it will have to be in the IO monad, as the value of the current time is always changing!

What you can do is to return a String in the IO monad:

> getCurrMonth :: IO String
> getCurrMonth = do
>    now <- getCurrentTime
>    return (formatTime defaultTimeLocale "%B" now)

then, from your top level (e.g. in main), you can pass the String around:

> main = do
>     s <- getCurrMonth
>     ... do something with s ...
like image 92
Don Stewart Avatar answered Sep 19 '22 08:09

Don Stewart


If you really want a pure function of that sort, then you need to pass in the time explicitly as a parameter.

import System.Locale (defaultTimeLocale)
import System.Time (formatCalendarTime, toUTCTime, getClockTime, ClockTime)

main = do now <- getClockTime
          putStrLn $ getMonthString now

getMonthString :: ClockTime -> String
getMonthString = formatCalendarTime defaultTimeLocale "%B" . toUTCTime

Notice how getMonthString can be pure since the IO action getClockTime is performed elsewhere.

I used the old-time functions, because I was testing it out on codepad, which apparently doesn't have the newer time package. :( I'm new to the old time functions so this might be off a couple hours since it uses toUTCTime.

like image 37
Dan Burton Avatar answered Sep 23 '22 08:09

Dan Burton