How can I implement a daily-updating timestamp on a website using bootstrap and javascript, particularly for review and blog posts?

I am looking to add a timer and date stamp feature to my website built with Bootstrap, using JavaScript or any other necessary tools. Typically, on platforms like Google or in blog posts, there is a small text under the user's photo and name indicating how long ago the post was made, such as '3 hours ago' or '1 month ago'. Please refer to the image below for an example.

https://i.sstatic.net/E8zOk.png

How can I implement this type of functionality on an HTML/CSS/Bootstrap website so that it automatically updates daily? For instance, I would like it to display '1 hour ago' one hour after posting and '1 month ago' once a month has passed, all without manual intervention.

Answer №1

An easy yet not so effective method to achieve this entails two steps:

  1. Create a function that accepts two timestamps and generates a string saying 'X time units ago'. Various libraries are available for this purpose.

  2. Periodically (using setInterval every 30 seconds, for instance), invoke the function with the parameters Date.now() and websiteTimestamp (assuming this is how your website's timestamp is named) and display the output in the designated view.

This approach may lead to unnecessary updates, but it's simple, right? While it might be suitable to indicate the age of a webpage, it may not be ideal in a chat application where showing the age of each message could cause issues.

Answer №2

I stumbled upon a similar solution in a previous post. Will this automatically update as I am hoping for?

Additionally, what should be the format of the 'date' input for the function (e.g. milliseconds, seconds, or a specific date format like YYYY-MM-DD)?

function timeSince(date) {

  var seconds = Math.floor((new Date() - date) / 1000);

  var interval = Math.floor(seconds / 31536000);

  if (interval > 1) {
    return interval + " years";
  }
  interval = Math.floor(seconds / 2592000);
  if (interval > 1) {
    return interval + " months";
  }
  interval = Math.floor(seconds / 86400);
  if (interval > 1) {
    return interval + " days";
  }
  interval = Math.floor(seconds / 3600);
  if (interval > 1) {
    return interval + " hours";
  }
  interval = Math.floor(seconds / 60);
  if (interval > 1) {
    return interval + " minutes";
  }
  return Math.floor(seconds) + " seconds";
}
var aDay = 24*60*60*1000
console.log(timeSince(new Date(Date.now()-aDay)));
console.log(timeSince(new Date(Date.now()-aDay*2)));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with synchronicity in javascript(node.js) and seeking assistance

I am faced with a challenge in my express.js app where I need to execute a script on the server, followed by running a couple of functions to derive some values. The process should be sequential, but I am running into issues as JavaScript seems to move on ...

What is the most effective approach for addressing errors in both the server and client sides while utilizing nodejs and express?

Seeking the most effective approach for handling errors in a response - request scenario. Here is an example of a route that receives a request: app.get('/getInfo', function (req, res, next) { let obj = {} try { obj = { ...

Ensuring that a nested div adjusts responsively within a static parent container

I am working on a project that involves HTML, CSS, and JS code. Here is the structure of my code: HTML: <div id="blockcart-wrapper"> <div class="blockcart cart-preview"> <div class="header"> <a rel="nofollow" href="#"> ...

The term "this" in the global scope versus within a function in the Node.js environment

console.log(this) // {} function abc(){ console.log(this) } abc() // global The concept of this can vary between the global space and inside a function in Node.js. console.log(this === module.exports) // true function abc(){ ...

Tips for aligning three <p> elements side by side using flexbox

I need assistance with aligning three boxes next to each other, each containing an image, header, and text. The issue arises when resizing the browser, causing the content in box 2 and 3 to be positioned higher than box 1. Below is the code I have been us ...

accurate JSONP reply

Currently, I am experimenting with JSONP locally to receive a correct response and pass it into my callback function jsonp_callback. I am referencing code from: How do I set up JSONP? header('content-type: application/json; charset=utf-8'); $dat ...

Aligning a large checkbox to the left in Bootstrap 4 styling

Bootstrap 4. <div class="form-group"> <label asp-for="Enabled" class="control-label"></label> <input asp-for="Enabled" class="form-control" type="checkbox" /> <span asp-validation-for="Enabled" class="text-danger"> ...

Performing updates on Meteor.users collection while handling a promise rejection (leveraging fcm-push with Meteor)

My current project involves the use of an NPM package called fcm-push in order to send FCM notifications to different mobile devices based on specific messages. Everything works fine when the message is successfully sent, but if the sending fails due to th ...

Invoking a nested function within an array

I need to trigger a function with a button click. The function I want to call is nested within another function, which is part of an array. demo = { volej: function(param) { (new initChartist).users(param); }, initPickColor: function(){ ...

Having difficulty clicking on the logo due to a CSS problem

HTML Code <div class="app-header-logo"> <a href="/home"><img ng-src="img/..."/></a> </div> CSS Styles .app-header-logo { width: 48px; height: 64px; padding: 8px 0px 8px 0px; margin: 0px 16px 0px ...

Tips for implementing jQuery on HTML loaded post document.ready():

I've encountered a scenario where I have multiple HTML elements being rendered by a JavaScript function on the page: <a href="#" class="test1">Test</a> <a href="#" class="test2">Test</a> <a href="#" class="test3">Test< ...

Is there a way to easily identify the error in my Express application that is preventing my hbs template from running properly?

I am facing an issue with my express code where it is not rendering the data properly. Can someone please assist me in resolving this error? Your help will be greatly appreciated! let express=require('express'); let app=express(); ...

Wait for the canvas to fully load before locating the base64 data in HTML5

Wait until the full canvas is loaded before finding the base64 of that canvas, rather than relying on a fixed time interval. function make_base(bg_img, width, height) { return new Promise(function(resolve, reject) { base_image = new Image(); base_imag ...

Create a layout using CSS that features two columns. The left column should be fluid, expanding to fill all remaining space, while the right column should be fixed

I need to ensure that the Online Users div always remains at a fixed size of 200px, while allowing the chat window next to it to resize dynamically based on available space. Essentially, I want the chat window to adjust its width as the window is resized, ...

Creating a Wordpress Metabox that utilizes radio inputs generated with Javascript instead of the traditional checked() function in Javascript as an alternative

Despite my efforts to find a solution on various forums, I am still stuck with this issue without making any progress. The code snippet below contains two Radio inputs. These inputs are generated on the post edit page of Wordpress CMS and their values com ...

Implementing a FadeOut effect for the clicked link

When clicking on each link, I want the same link to fadeOut() after clicking on the ok button in the myalert() function. If clicked on cancel, it should not fadeOut(). How can I achieve this using the myalert() function? For example: http://jsfiddle.net/M ...

How can I incorporate a counter into my ng-repeat loop in Angular?

Do you know where I can find documentation on adding a numbered count to each item returned by an ng-repeat in Angular? This is not like assigning an Id, but more like, if 4 items are returned, each JSON object could include a number before the data. Her ...

Using jQuery to target multiple div elements sharing a common class that are separate from the currently selected div

I am facing a challenge with a div that has a variable number of specific children that I need to toggle between hide and show. It's difficult to explain, but the following code provides a clear example. <div class="item_content_container"> ...

Is there a way to highlight a table row depending on a condition using jquery or php?

I am looking to implement a blinking effect on a specific table row based on the value contained in the row matching a PHP variable. For example, if the PHP variable has a value of 'ABC', I want the table row containing the text 'ABC' t ...

What steps can I take to resolve this error when utilizing an npm package in client-side JavaScript?

Just when I thought I was getting the hang of socket.io, I hit a roadblock on the client side. Following my instructor's advice, I installed socket.io-client package for my project. But when I tried to use it in my client-side JS code, I encountered a ...