Obtain the current date and time for a 24-hour loop using JavaScript

I have a drop-down menu with options such as "Last 24 hours", "Last 48 hours", etc. When I select "Last 24 hours" from the drop-down, I would like to retrieve all dates from now until yesterday in one-hour intervals.

Here is my attempt at achieving this:

   var todayDate = new Date();
    if(type=="hours"){ // for hours-based drop-down
        var oneDayAgo = new Date(todayDate.getTime());
        oneDayAgo.setDate(todayDate.getDate() - 1);
        console.log("oneDayAgo"+oneDayAgo);
        var hours = todayDate.getHours();
        for(var i = hours; i <= hours+24; i++) {
            if(i<25){
                var newHours=i;
                var newDates=todayDate.getFullYear() + "-" + ("00" + (todayDate.getMonth() + 1)).slice(-2) + "-" + ("00" + todayDate.getDate()).slice(-2) + " " + ("00" +newHours).slice(-2) + ":" + ("00" + todayDate.getMinutes()).slice(-2) + ":" + ("00" + todayDate.getSeconds()).slice(-2);
                console.log(newDates);
            }else{
                var newHours=i-24;
                var newDates=oneDayAgo.getFullYear() + "-" + ("00" + (oneDayAgo.getMonth() + 1)).slice(-2) + "-" + ("00" + oneDayAgo.getDate()).slice(-2) + " " + ("00" +newHours).slice(-2) + ":" + ("00" + oneDayAgo.getMinutes()).slice(-2) + ":" + ("00" + oneDayAgo.getSeconds()).slice(-2);
                console.log(newDates);
            }
        }
    }

My desired output is as follows:

If the current date and time are 2014-04-27 13:07, then the expected output should be: 2014-04-27 13:07, 2014-04-27 12:07, 2014-04-27 11:07 , 2014-04-27 10:07.... 2014-04-26 13:07

Any help or suggestions on how to achieve this would be greatly appreciated. Thank you.

Answer №1

function retrieveDate(hours) {
  var endDate = new Date();
  var startDate = new Date();
  startDate.setTime(startDate.getTime() - (hours * 60 * 60 * 1000));
  var dataList = [];
  
  while (endDate >= startDate) {
    dataList.push(endDate.getFullYear() + "-" + ("00" + (endDate.getMonth() + 1)).slice(-2) + "-" + ("00" + endDate.getDate()).slice(-2) + " " + ("00" + endDate.getHours()).slice(-2) + ":" + ("00" + endDate.getMinutes()).slice(-2) + ":" + ("00" + endDate.getSeconds()).slice(-2));
    
    // consider using moment.js library to format date
    endDate.setTime(endDate.getTime() - (1 * 60 * 60 * 1000));
  }

  return dataList;
}

var last24HoursDates = retrieveDate(24);
var last48HoursDates = retrieveDate(48);

console.log(last24HoursDates);

Answer №2

Check out this live example that could meet your requirements.

//retrieve type and hoursOption from dropdowns
var type = 'hours'
var hoursOption = 48;

var todayDate = new Date();

if(type=="hours"){ // for hours based drop-down

    var hours = todayDate.getHours();
    for(var i = hours; i <= hours + hoursOption; i++) {
            todayDate.setHours(todayDate.getHours() - 1)
        var newDates = todayDate.getFullYear() + "-" + ("00" + (todayDate.getMonth() + 1)).slice(-2) + "-" + ("00" + todayDate.getDate()).slice(-2) + " " + ("00" + todayDate.getHours()).slice(-2) + ":" + ("00" + todayDate.getMinutes()).slice(-2) + ":" + ("00" + todayDate.getSeconds()).slice(-2);
            console.log(newDates);

    }
}

In the for-loop, I introduced the variable hourOption which is derived from the dropdown options such as 24, 48, 72, etc.

Within the loop, each iteration subtracts one hour from the current time of todayDate, resulting in a countdown display of hours.

Answer №3

Success! This method did the trick.

let startTime = new Date("2022-01-01T00:00:00");
    let endTime = new Date("2022-01-01T23:00:00");
    
    for (let now = startTime; now <= endTime; now.setHours(now.getHours() + 1)) {
        console.log(now);
    }

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

Changing the structure of an array of objects

Currently, I am dealing with an API that provides an array of objects structured like this: [{match_id: "255232", country_id: "41", country_name: "England", league_id: "152", league_name: "National League", match_date: "2020-01-01", match_status: "", matc ...

TypeScript Implementation of ES6 Arrow Functions

Just diving into Typescript, I'm struggling to figure out the solution. I tried researching and looked into destructuring, but still unable to make it work. import React from "react"; import { StyleSheet, Text, View } from "react-native"; const st ...

The parameter 'File' cannot be assigned to a parameter of type 'string'

I need help resolving an issue while attempting to upload a photo along with some additional information. The error message I am encountering is "Argument of type 'File' is not assignable to parameter of type 'string'." My frontend is ...

Navigating between multiple views can be easily achieved with Angular's ui.router

I'm encountering an issue with the ui.router plugin. I set up what I believed were 3 states to switch between: $stateProvider .state('rackOrShelf', { url: '/information', templateUrl: 'Scripts/ ...

Is it possible to invoke an AngularJs service by clicking a button?

Recently, I've been working on some AngularJS code involving a service and controller. angular.module('myModule', []).service("AttendanceService", function ($http) { this.getdata = function () { return $http({ ...

Retrieving URLs of mapped image array from Firebase using React

I have successfully implemented an image slider in my website using https://github.com/kimcoder/react-simple-image-slider. This slider takes an array of images as input through Object.values(images). However, I now want to switch to using a grid array prov ...

Notification Click Event for PWA Service Worker

I am attempting to display a notification and trigger an action when it is clicked. try { navigator.serviceWorker.getRegistration() .then(reg => { reg.showNotification("Check out the video clip!", { body: "Cl ...

Transitioning to TypeScript has brought the promise of imports returning once again

I've been facing some challenges while migrating my extensive project to TypeScript, particularly with handling imports. Being relatively new to programming, I'm unsure if my previous approach was considered bad practice. Previously, I organized ...

Unresolved styles in React component linked to styles.css file

As I dive into creating a registration page in ReactJS, I encounter a frustrating issue with my styles not applying correctly from the styles.css file. Let's take a look at my RegisterPage.jsx component: export default function RegisterPage() { ret ...

Tips for storing and retrieving high scores in a JavaScript game

I've just finished creating a JavaScript snake game and now I'd like to add a "scores" option that displays the top 10 players along with their names and scores. My initial plan was to create an object containing the player's name and score ...

Is it possible for an angular directive to transmit arguments to functions within specified expressions in the directive's attributes?

I am working on a form directive that utilizes a specific callback attribute with an isolate scope: scope: { callback: '&' } This directive is placed within an ng-repeat, where the expression passed in includes the id of the object as an ar ...

What could be the reason for the Express function Router() returning a value of undefined?

Currently, I am working with TypeScript and Express to develop an API that adheres to the principles of Clean Architecture. To organize my application, I have structured each route in separate folders and then imported them all into an index.ts file where ...

Change Node.js version to 6.11.5 on a Windows system

My current node version is v8.2.1, but Google Cloud Functions only supports v6.11.5. I need to switch my node version accordingly and preferably do it using npm. How can I achieve this? I have explored How to change to an older version of node.js for guid ...

Exploring ways to create additional file upload fields with distinct names through JavaScript

My latest project involved creating a button that allows users to add a file upload field, a separate button to remove a file upload field, and a counter to keep track of the total number of file upload fields. However, it appears that the fields are not b ...

The information contained in HTML element lists and paginated using bootstrap and React does not persist after changing pages. This issue affects the functionality of React + Bootstrap

My "Pagination" Component manages the pagination of items (typically test questions) passed in as parameters. The component displays these items on the screen based on the current page. const dataTest = [ <><div className="row&quo ...

The JSP page does not redirect after an Ajax post request has been made

When submitting a form with basic AJAX post, I am facing an issue where the redirection to the JSP does not occur upon success. Setting the redirect programmatically seems to create a new JSP instead of utilizing the existing one with POST data. After debu ...

Display the item prior to fetching the AJAX response

Whenever a user clicks on my button, I want to display an item that is connected with my AJAX response. The div should be visible after clicking the button and then hidden once the entire page has finished loading. This is my AJAX code: document.getEleme ...

One of the components in React failed to render even though data was successfully passed to both

I utilized React to create a submenu list. The parent component receives JSON data and passes it down to two child components. However, only one of the child components successfully displays the data while the other fails to do so. Both child components ...

Why isn't my mongoose update function functioning properly?

After reviewing numerous questions on stackoverflow, I've made some modifications to this simple query that just won't work. I'm at a loss as to why... router.get('/users/:username/suspend', function(req, res){ var userna ...

Using force-directed layout to access and retrieve specific data from external or internal data sources

Just starting out with d3js and currently working on modifying the Force directed layout found at http://bl.ocks.org/mbostock/1153292 I have managed to make it so that when I hover over the node circles, the corresponding source value filenames should app ...