waffledood
waffledood

Reputation: 283

Fixing date & time format in HTML

Context of Question

Hi all, I'm building a Twitter clone. I'm using JavaScript to create & insert a new Tweet into the news feed.

After inserting the new Tweet into the news feed, I noticed the date & time format is different after refreshing the page. Examples below for reference:

Tweet after inserting into news feed & before refreshing the page

enter image description here

Tweet after refreshing the page

enter image description here

The Tweet in JSON format looks like this

  {
    "id": 56,
    "user": "admin",
    "content": "yes",
    "date": "Feb 07 2023, 12:26 AM",
    "likes": 0
  }

I'm using Django as the backend & the how a Tweet gets serialized is as follows:

def serialize(self):
        return {
            "id": self.id,
            "user": self.user.username,
            "content": self.content,
            "date": self.date.strftime("%b %d %Y, %I:%M %p"),
            "likes": self.likes
        }

Now, I'm not sure what's causing this mismatch of date & time format:

Django template for Tweet

  <small class="text-muted tweet-date">{{tweet.date}}</small>

JavaScript code for inserting Tweet

function createTweet(tweetJsonObject) {
    // clone Tweet from Tweet template
    let newTweet = document.querySelector(".tweet-template").cloneNode(true);
    newTweet.style.display = "block";
    newTweet.querySelector(".tweet-date").textContent = tweetJsonObject.date;
    newTweet.querySelector(".tweet-content").textContent = tweetJsonObject.content;
    newTweet.querySelector(".tweet-likes").textContent = tweetJsonObject.likes;
    newTweet.dataset.id = tweetJsonObject.id;
    // remove tweet-template & add tweet class
    newTweet.classList.remove('tweet-template');
    newTweet.classList.add('tweet');

    return newTweet;
}

Upvotes: 0

Views: 55

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32294

Use the date filter to format a date in a Django template

The following format string should match the output of the one used in your JSON

  <small class="text-muted tweet-date">{{ tweet.date|date:"M d Y, h:i A" }}</small>

Upvotes: 1

Related Questions