1

How do I format .created_at to produce the same time format as my Ruby code?

Javascript / jQuery

<script>
  setInterval(function () {
    fetch('/pages/markets.json')
    .then((response) => response.json())
    // .then((data) => console.log(data))
    .then((data) => { 
      $('#container').html('')
      data.forEach((item) => { 
        $('#container').append('<li><div id="created" class="text-xs mb-1">' + item.created_at + '</div><div id="text" >' +  item.tweet_text +'</div></li>')
      })
    });
  }, 10000); 
</script>

Returns: 2022-08-15T13:55:32.089Z

Ruby on Rails

t.created_at.in_time_zone("Eastern Time (US & Canada)").strftime('%I:%M %p')

Returns: 01:30 PM

1 Answers1

1

I think it's better to send formatted date to frontend from backend

But if you can't, you can use moment.js

moment(item.created_at).tz('America/New_York').format('hh:mm A')

or

moment.tz(item.created_at, 'EST').format('hh:mm A')

Please look:

https://momentjs.com

https://momentjs.com/timezone

You can also use vanilla JS Intl.DateTimeFormat

Intl.DateTimeFormat('en', { hour: '2-digit', minute: '2-digit', timeZone: 'EST' }).format(new Date(item.created_at))
mechnicov
  • 12,025
  • 4
  • 33
  • 56
  • FYI: Even [moment.js](https://momentjs.com/docs/#/-project-status/) recommend against using moment.js – freedomn-m Aug 15 '22 at 18:46
  • Thank u @mechnicov last answer worked for me. Finally. Only probably atm is that it shows 1 hour wrong. How do I fix that? ET atm should be 3:11, but that code shows me 2:11. – Emil Ståhl Myllyaho Aug 15 '22 at 19:09
  • 1
    @EmilStåhlMyllyaho I'm not sure but may be timezone or summertime problem, try `'America/New_York'` instead of `'EST'` – mechnicov Aug 15 '22 at 19:14