Search code examples
parsinghaskelltimebytestring

Haskell Convert ByteString To UTC Time


I have been trying to make a function in Haskell to take a ByteString which is a datetime and convert it to UTC time taking into account the time zone from the original encoding. I am very new to Haskell so I may be making a really basic mistake.

convertStringToUtc s =
  do
    estTimeZone <- hoursToTimeZone -5
    time <- read $ B.unpack(s)
    localTimeToUTC estTimeZone time

The error I get is:

Couldn't match expected type `Int -> b'
       against inferred type `UTCTime'
In the expression: localTimeToUTC estTimeZone time
In the expression:
    do { estTimeZone <- hoursToTimeZone - 5;
         time <- read $ B.unpack (s);
         localTimeToUTC estTimeZone time }

Solution

  • First, the -5 needs to be in parentheses, otherwise it's parsed as trying to subtract 5 from the hoursToTimeZone function, which explains the type error.

    Also, all functions here are pure, so they don't need to be in a monadic do{...}. Just use a let expression if you want to explicitly name the steps.

    convertStringToUtc s = 
        let estTimeZone = hoursToTimeZone (-5)
            time = read $ B.unpack s
        in  localTimeToUTC estTimeZone time