Format datetime into local representation

Hi!
I have a datetime in milliseconds and I’d like to display it to a user in their browser locale.
I’m converting it into DateTime using purescript-datetime: https://github.com/purescript/purescript-datetime
Then I’m formatting it using formatDateTime "YYYY-MM-DD HH:mm" from https://github.com/slamdata/purescript-formatters

The problem is that everything is formatted in UTC time.
Is there a similar library which would allow to use user’s locale for formatting?

Cheers,
Leonti

I opted to use the ffi for this.

You would find out what the offset is and use adjust before formatting it https://pursuit.purescript.org/packages/purescript-datetime/4.0.0/docs/Data.DateTime#v:adjust. Alternatively you could convert it to a JSDate https://pursuit.purescript.org/packages/purescript-js-date/6.0.0/docs/Data.JSDate#v:fromDateTime

Hi @Leonti,

There is some discussion about time zones and the purescript-datetime library in the following issue might be helpful to you. Knowing the right offset for a city requires querying a non-trivial data set, and performing calculations on a value having this offset as part of the value can be complicated. The PureScript library ecosystem does need an implementation of this, so we must wait for someone to tackle a proper implementation. Until then, you can use another language’s library using the FFI or write a quick-and-dirty implementation of a LocalDateTime. Personally, I chose to use a MomentJS wrapper, which I should note might bring a huuuuuge timezone data set into your JS bundle, though it should be possible to trim it.

Thanks guys!
The solution that I have at the moment is to use purescript-js-date (thanks @natefaubion) to get JSDate:
https://pursuit.purescript.org/packages/purescript-js-date/6.0.0/docs/Data.JSDate#v:now combined with getTimeoneOffset
https://pursuit.purescript.org/packages/purescript-js-date/6.0.0/docs/Data.JSDate#v:getTimezoneOffset

After that I use adjust before formatting:

formatMilliseconds :: Number -> Minutes -> String
formatMilliseconds timestamp timezoneOffset = fromMaybe "date-error" do
  dt <- map toDateTime (instant $ Milliseconds timestamp)
  adjusted <- adjust timezoneOffset dt
  pure $ case FDT.formatDateTime "YYYY-MM-DD HH:mm" adjusted of
    Left error -> error
    Right formatted -> formatted

At the moment I don’t need more advanced localization, so timezone offset is all I need :slight_smile:
Thanks for your help!

Cheers,
Leonti

3 Likes