Calculate the time difference between time A and time B using DayJs

This is a common issue, but the unique aspect of this situation is as follows:

I am attempting to calculate the hours between 12:00 (timeA) and 20:00 (timeB). A basic

dayjs(timeA).diff(timeB, 'hours')
yields 8 hours.

The challenge arises when calculating the hours between 20:00 and 02:00 midnight, which results in 18 hours instead of the desired 6 hours.

Is there a method using dayJs to achieve the correct calculation in this scenario?

Answer №1

When utilizing dayjs, it automatically converts the time you provide to it into the time of day. In the code snippet below, I have compared two times and adjusted one of them to ensure the time difference is calculated correctly. This method works effectively only if the times you input have a specific order, with one coming before the other.

function calculateTimeDifference(timeA, timeB) {
  const ta = dayjs(timeA, 'HH:mm');
  let tb = dayjs(timeB, 'HH:mm');

  if (ta.isAfter(tb)) tb = tb.add(1, 'd');

  const difference = dayjs(tb).diff(ta, 'hours');

  console.log(`The time difference between ${ta.format('YYYY-MM-DD HH:mm')} and ${tb.format('YYYY-MM-DD HH:mm')} is ${difference} hours`);
}

calculateTimeDifference('12:00', '20:00');
calculateTimeDifference('20:00', '02:00');
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.8/plugin/customParseFormat.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script>
  dayjs.extend(window.dayjs_plugin_customParseFormat)
</script>

Answer №2

After typing out my thoughts, it hit me that the solution was simply 24 - 18. Utilizing the rubber duck method, I suppose. Nevertheless, I decided to share it here in case someone else had trouble figuring it out.

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

What are the steps for testing React components when they are wrapped by ThemeProvider/withStyle?

Is there a way to properly test a component that is wrapped with withStyle, as it seems the theme object does not pass through the component. Any suggestions on best practices for achieving this? I am considering using createShallow() and dive() methods t ...

The custom error page in NextJS is failing to display

In my custom pages/404.ts file, I have coded the following: export default function NotFound() { return <h1>404 - Page Not Found</h1> } Additionally, there is another page that displays a 404 error when the organization is null: import Error ...

Shifting an element to the right before revealing or concealing it with Jquery Show/Hide

$(document).ready(function(){ var speed = 700; var pause = 3500; function removeFirstElement(){ $('ul#newsfeed li:first').hide('slide', {direction: "up"}, speed, function() {addLastElement(thi ...

Ways to specify the specific option within a select field

Here is my question: <select name="currency" id="currency"> <option value="AUD"&lgt;AUD</option> <option value="BDT"&lgt;BDT</option> <option value="EUR"&lgt;EUR</option> & ...

Converting data into a multidimensional array in AngularJS: A comprehensive guide

Struggling to convert a JSON array into a multidimensional array, looking for some guidance. I attempted using _.groupBy in underscore.js, but it's not proving successful with the nested array. If there is any way to convert from the given data [{ ...

Steer clear of changing props directly in VueJS to prevent unintended

I am working with a component that has props, and I need to change the value from false to true. However, I encountered a message in the Chrome console advising against mutating a prop directly because it will be overwritten whenever the parent component r ...

Utilizing the no-data-text attribute in v-combobox with Vuetify: Tips and tricks

My application includes a simple combobox, and I am trying to set a default text message to display when there are no entries in the items props. To achieve this goal, I utilized the no-data-text prop by passing a specific variable to it. <v-combobox ...

Creating Virtual Nodes from a string with HTML tags in Vue 2.5: A Step-by-Step Guide

Having some trouble creating a functional component that displays the Feather Icons package - I'm stuck on the final step. Here's what I have so far: This is my FeatherIcon.vue component. <script> const feather = require("feather-icons"); ...

CKeditor with Kcfinder

Although I've seen similar topics, none seem to match my exact situation. I recently added CKEditor to my website and wanted to integrate KCFinder as the file manager. Following the instructions on KCFinder's website, I copied the necessary file ...

Receiving null value with Web API POST using [FromBody]

Below is the code for my WebAPI in C#: [Route("")] [HttpPost] public void SaveTestRun([FromBody] object data) { inputResultsToDatabase(data); } This is the ajax request I am making: sendTestData() { t ...

Designing an interactive 3D space using JavaScript

I'm currently developing an app that allows users to visualize different wallpapers in a 3D room setting. The concept involves placing the user inside a virtual space with four walls, where they can drag and look around, as well as change wallpapers v ...

Retrieving a string from a variable, which was imported from JS, to use as a key within

Is it possible to assign a variable as the key of an object in JavaScript? I have imported constants from a 'definitions.js' file and I need to use these constants as keys: import * as cons from '../scripts/definitions.js' export def ...

Guidelines for cycling through a series of HTTP requests and effectively saving the data from each cycle into an array

Utilizing Spotify's API search feature, I am working with an array of SongSearchParams that consist of title and artist parameters: export class SongSearchParams { public title: string; public artist: string; constructor(title: string, a ...

Utilizing Material UI's (MUI) date picker in conjunction with react-hook-form offers a

I'm currently developing a form with a date field utilizing MUI and react-hook-form for validation. I have experimented with two different methods of rendering the field, but when I try to submit the form, the expected value is not being returned: Me ...

Canvas - Drawing restricted to new tiles when hovered over, not the entire canvas

Imagine having a canvas divided into a 15x10 32-pixel checkerboard grid. This setup looks like: var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var tileSize = 32; var xCoord var yCoord ...

What is the way to execute a function *once* all my ajax call functions have finished?

I am utilizing jQuery to execute some ajax requests: var information = {}; function process_information(item){ information[item.id] = item; } function perform(){ var calls = []; for(var i = 0; i < 10; i++){ var call = $.get(URL, ...

Retrieve the chosen item along with its quantity

I'm currently working on building a shopping cart application similar to this example using React.js. index.js: (Sending each product to the product component) {products.length > 0 ? products.map((product) => ( <Produ ...

Issues with the styling of HTML code

Our website features a main menu with submenus that are intended to be displayed only when hovering over the main menu. However, upon loading the site, the submenu is already visible causing an issue. We need the submenu to appear only when the main menu i ...

To style the input box, apply the CSS properties "filter: alpha(opacity=70);" and "background-image: url(image.png);"

Individual functionality for both the form and css has been achieved, but when trying to implement them together, they do not work as intended. This integration is specifically for a windows sidebar gadget. Here is the structure of the form: <form nam ...

Transmit text from tinyMCE through AJAX in MVC architecture with PHP

I am currently facing an issue while trying to send POST data in the form of an array containing email elements such as subject and message. The problem arises when using tinyMCE for the subject part, which is not being sent through successfully. All other ...