Displaying the countdown of days and hours until a specific date is just a matter of using

Currently, I am tackling a project that necessitates a specific text response related to a date object.

"1 day 7 hours away" --- This format is crucial; alternatives such as "31 hours away" or "1 day away" will not suffice. -- For language switching purposes between English and German, I am utilizing moment js along with the moment.js language locale:

moment.locale('de')

In order to achieve this, I have generated a fabricated date object using moment js.

  var futureDate = new Date()
  futureDate.setDate(futureDate.getDate() + 1)// add a day
  futureDate.setHours(7)// add 7 hours

However, when attempting to display the moment js result,

moment(futureDate).endOf('day').fromNow()

The output simply states "in a day."

How can I adjust the moment function to properly handle 1 day 7 hours, along with potentially restructuring the sentence?

--- Here is an example of code snippet attempt

moment.locale('de') // toggle between en and de -- english and german

var futureDate = new Date()
futureDate.setDate(futureDate.getDate() + 1)// add a day
futureDate.setHours(7)// add 4 hours

// Provides results in hours
console.log(moment(futureDate).endOf('day').fromNow()); 
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Second test utilizing difference calculation

moment.locale('de') // toggle between en and de -- english and german

var a = moment();
var b = moment(a).add(31, 'hours');

// Provides results in days
console.log(b.diff(a, 'days'));
console.log(b.diff(a, 'days', true)); 
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Answer №1

To customize how moment displays relative time, you can utilize the relativeTimeThreshold and relativeTime options (accessible through moment.updateLocale).

In your specific scenario, consider the following steps:

  • Adjust the threshold to show differences in seconds (refer to: How to make moment.js display relative time in seconds?).
  • Create a duration object using moment.duration(Number, String).
  • Utilize the moment-duration-format plugin for displaying the duration value as per your preference.

Here is an example showcasing these concepts:

var momEn = moment().add({d:1, h:7});
var momDe = moment().locale('de').add({d:1, h:7});

console.log(momEn.fromNow()); // in a day
console.log(momDe.fromNow()); // in einem Tag

// Adjusting relativeTimeThreshold
moment.relativeTimeThreshold('s', 60*60*24*30*12);

// Updating relative time formats
moment.updateLocale('en', {
  relativeTime : {
    s: function (number, withoutSuffix, key, isFuture){
      return moment.duration(number, 's').format('d [day] h [hour]');
    },
  }
});

moment.updateLocale('de', {
  relativeTime : {
    s: function (number, withoutSuffix, key, isFuture){
      return moment.duration(number, 's').format('d [Tag] h [Uhr]');
    },
  }
});

console.log(momEn.fromNow()); // in 1 day 7 hour
console.log(momDe.fromNow()); // in 1 Tag 7 Uhr
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

Keep in mind that manual updates are required for each locale that you wish to support.

Answer №2

If you want to calculate date differences, you can utilize either moment-duration-format or the moment.diff function as shown below:

let futureDate = new Date ()
futureDate.setDate (futureDate.getDate () + 1)// add a day
futureDate.setHours (7)
let start = moment ()
let end = moment (futureDate)

// Method 1: Using moment-duration-format

console.log (moment.duration (end.diff (start)).format ('d [days] hh [hours]', { trim: false }))

// Method 2: Using diff without moment-duration-format

let hoursDuration = end.diff (start, 'hours')
console.log (Math.floor (hoursDuration / 24) + ' days ' + (hoursDuration % 24) + ' hours')
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

The first method necessitates the installation of the moment-duration-format module, while the second accomplishes everything using solely moment.js. Remember to execute

npm install moment-duration-format
before requiring it.

Answer №3

Note: If you prefer using Moment.js, they offer the moment#diff method for calculating the difference between dates:

var firstDate = moment([2007, 0, 29]);
var secondDate = moment([2007, 0, 28]);
firstDate.diff(secondDate, 'days') // 1

Source:


An alternative solution would be to use countdown.js:

var futureDate = new Date()
futureDate.setDate(futureDate.getDate() + 1)// add a day
futureDate.setHours(7)// add 7 hours
var timeElapsed = countdown(Date.now().toString(), futureDate, countdown.DAYS|countdown.HOURS);

console.log(timeElapsed);

The output of timeElapsed is an informative object; for example:

  days: 0
  end: Tue Jul 04 2017 07:17:41 GMT+0300 (EEST)
  hours: 12
  start: Mon Jul 03 2017 19:17:41 GMT+0300 (EEST)
  units: 18
  value: 43200000

You can then format this data as needed for your application.

If you decide to go with countdown.js, it's available on a CDN here:

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

At times, Express.js may display an error message stating "Cannot GET /"

My objective is to have http://localhost:3000/app display myFile.html and http://localhost:3000/api return "It worked!". I currently have two files set up for this: App.js: const http = require('http'); const fs = require('fs&apo ...

I encountered an unexpected token error while using JavaScript syntax with objects

In my current coding project, I have encountered an issue while attempting to utilize an object from a different JavaScript file. Despite importing the necessary function from this external file, there seems to be a syntax error present. Can anyone offer ...

Utilizing AngularJS to access the corresponding controller from a directive

When I have HTML structured like this... <div ng-app="myApp"> <div ng-controller="inControl"> I enjoy sipping on {{beverage}}<br> <input my-dir ng-model="beverage"></input> </div> </div> a ...

Retrieving the Short Date Format from the user's device or browser within a React application

Currently, I am in the process of utilizing reactjs along with material UI datepicker. My objective is to transmit the short date format to the datepicker component, such as format="MM/dd/yyyy". In addition, I wish to employ the pre-existing date ...

Monitoring the flow of data between Angular JS resources and the promise responses

In my application, there is a grid consisting of cells where users can drag and drop images. Whenever an image is dropped onto a cell, a $resource action call is triggered to update the app. My goal is to display a loader in each cell while the update cal ...

Is there a method in AngularJS to submit form data when the input fields are pre-populated using a GET request?

How do I submit form data in AngularJS? I have a div that populates the input field from a GET request. Now, I want to send this data using a POST method. How can I achieve this? Below is the form div: <div class="row" ng-app="myApp" ng-controller="myC ...

Refreshing material ui select choices based on user input

Just getting started with Reactjs and I need some help. I have a material ui select element that has default values set, and when I click the 'ADD USER' button and submit, I can add new values to the select element. I'm also able to delete o ...

Looking to decrease Cumulative Layout Shift (CLS) on the NextJS website for enhanced performance

I have chosen to use NextJS with Mantine for my website development. Utilizing createStyles, I have added custom stylings and incorporated various mantine components into the design. After deploying the site on Vercel, I discovered that all performance me ...

Show component depending on the lifecycle of another component

I recently encountered a problem with one of my custom components. I developed a "Chargement" Component (Loading in French) for a project I am currently working on. The component is a basic circular spinner with a dark background that indicates to the use ...

The Alert Component fails to display when the same Error is triggered for the second time

In the midst of developing a Website using Nuxt.js (Vue.js), I've encountered an issue with my custom Alert Component. I designed a contact form on the site to trigger a specialized notification when users input incorrect data or omit required fields ...

Tips for obtaining a JSON response from a RESTful API in AngularJS by utilizing the $resource service

I have been working on my AngularJS code, and although I am receiving a response in the console, I am having trouble storing it in an array or JSON format. angular.module('user', ['ngResource']). config(function($httpProvider){ $h ...

Retrieving and assigning data values within an Angular JS service

Here is the service I created to fetch user details: angular.module('app') .factory('userDetailService', function($http) { var userData = {}; function getUserDetails(userId) { if (userId) { return $http.get ...

Merging two arrays by their corresponding IDs and indexes

Within my current project, I am working with two arrays. The first array, arr1, contains a questionID property that I need to use to combine it with arr2 based on the condition where arr1 questionID equals arr2 index. For example, if arr1 questionID is 1, ...

Unable to access current props within useEffect block

When I use useEffect with the parameter props.quizStep, my function fn (which is a keydown event listener) is unable to access the current value of props.quizStep. I'm puzzled as to why it's not working properly. Can you help me understand? Bel ...

The markers from KML exported from My Maps are not showing up on the Google Maps JavaScript API

I have a map on Google My Maps that I want to showcase through the Google Maps JavaScript API. This way, I can easily merge multiple maps into one and add paths/markers without needing to code it all manually. Test out the map I'm using by clicking t ...

How to send a PHP variable to Ajax and execute a corresponding PHP function in response

I have a set of database records that are being displayed in separate div elements on the page. Each record corresponds to a specific ID, with its information displayed inside the div. My goal is to create a delete button for each record that would allow ...

Error encountered when attempting to add document to Firebase database: admin:1. An unexpected FirebaseError occurred, stating that the expected type was 'Na', but it was actually a custom object

I am encountering an error when trying to add a document to my collection in Firebase. I have successfully uploaded an image to Storage and obtained the URL, but this specific step is causing issues. I have followed the code implementation similar to how F ...

What methods are available for identifying non-operational pointer-events?

According to this resource, Opera 12 does not support pointer-events, causing issues with my website. Interestingly, they do support the property in CSS but don't seem to implement it correctly. Modernizr's feature detection doesn't help in ...

``If you're looking to retrieve, modify, and display information in your Vue application with the help of

I'm facing an issue where I am trying to retrieve data using the axios get request and then updating it based on the response of another axios get request. However, I am unable to display the data from the second request. The following is a snippet o ...

What sets apart an object within the scalajs scope from the exact same object within the js.global scope?

Attempting to create a basic example for rendering a cube using the THREEJS library. package three import org.scalajs.dom import scala.scalajs.js import scala.scalajs.js.Dynamic._ import scala.scalajs.js.annotation.JSName ... object ThreeExample { d ...