Seize the Moment.js

Converting Ruby Strings to Local Time in React

Matthew Sedlacek
Level Up Coding

--

Photo by Fabrizio Verrecchia on Unsplash

In a recent coding challenge, I was tasked with building a chat application. One of the requirements was to show the time the message was posted. My first thought was to use the Ruby created_at string provided by my fetch. However, that string looks like this:

Created_at string from Ruby on Rails Backend

My next thought was to convert the date in my backend rails model, but this also proved problematic as the times that came through were in UTC.

# app/models/application_record.rbclass ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def created_at
attributes['created_at'].strftime("%Y-%m-%d %H:%M %Z")
end
end
Rendering in Chat Application

In addition, the time zone I was living in was different from the time zone of the company I was applying to.

My solution to this problem came in the form of Moment.js. Moment is a JavaScript date and time library specifically built to deal with these kinds of issues. You can see their helpful docs here or some examples down below.

Moment.js examples from https://momentjs.com/

In my chat application, another requirement was to display only the most recent ten messages, with the most recent being on the top and the least recent on the bottom. My app needed to allow for many users to post at once, and I, therefore, needed to be very precise with how I sorted my posts. Thus, I sorted the Ruby strings I mentioned before and did not use Moment.js till the lowest possible component. The component I used was a function component. See below for the source code.

// src/components/chatbox/MessageCard.jsimport React from "react";
import Grid from "@material-ui/core/Grid";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
const moment = require("moment");const MessageCard = (props) => { let dateString = props.timestamp; let dateObj = new Date(dateString); let momentObj = moment(dateObj); let momentString = momentObj.format("MMMM Do YYYY, h:mm:ss a"); return ( <ListItem> <Grid item xs={12}> <ListItemText align="left" secondary={momentString}>
</ListItemText>
</Grid> </ListItem> );};export default MessageCard;
Final Rendering in Chat Application

I hope this blog will help you with formatting dates and times in future applications. In an upcoming blog, I will discuss WebSockets, which enabled me to log messages as they occurred and share those messages with everyone connected to the app.

--

--