We are going to dive into converting a Ruby datetime object to a JS date object. I used React JS for my latest application. One of the features for the app is a schedule of games for a local little league. I used a Ruby backend with a React JS frontend.
Of course for a game schedule the time of the games is very important. I thought there was going to be no issue. When I started implementing the games in my frontend I noticed that the time was off from the backend. Let's go step by step through my process.
- First of all I have an array of games so I need to map through those games and pull out the pertinent information for the game schedule. For now we will just focus on the time aspect. I did this with a simple map function in React.
this.props.games.map(game => game.date)
Here the problem is we get an unreadable string.
You can see that is June 12, 2021 at 14:00(2:00pm). This is the correct date so now we just have to convert it to JS to make it look good.
Enter Moment.js. This is a very simple way to convert your Ruby time to JS time. Here is how to use it in React JS.
First install it to your application.
- npm install moment --save or
- yarn add moment
Then import Moment.
import Moment from 'moment';
Now take game.date and use it as an argument in the Moment function.
Moment(game.date).format('MMMM DD, LT')
Here is what we get back
June 12, 6:00 AM
Fixing this is simple but pretty difficult to find out how while googling.
- Now that we have our time coming through with the correct format we just have to figure out how to make it read the correct time of 2:00pm.
I will just skip right to it for you.
When Ruby sends a datetime object from the backend to the frontend it will be in UTC time which is Coordinated Universal Time. If your time zone doesn't line up with that then you have come to the right place.
Moment.js has a lot of functionalities where you can use a timezone function the regular moment function and also a parseZone function.
What we want is the parseZone function. What this does with the Ruby datetime object is takes the time coming in and uses that exact time without converting it to your local timezone. For me being in Alaska we are 8 hours earlier than UTC which is why my time kept coming back incorrect. parseZone says hey we don't want any conversions just show me what the Ruby backend is saying exactly.
This is still a function of Moment.js so everything above is needed. This is what the final function will look like.
Moment.parseZone(game.date).format('MMMM DD, LT')
Which will give us
June 12, 2:00 PM
Exactly what we are looking for!
The Moment.js docs also have a ton of formatting options and are something to definitely check out if this is something you may be using!
Top comments (0)