Verify if the date and time in string format is the exact same as noon

In my data collection, there are multiple objects each containing a specific date and time value:

[
  {dt: "2019-11-29 12:00:00"},
  {dt: "2019-11-29 3:00:00"},
  {dt: "2019-11-29 6:00:00"},
  {dt: "2019-11-30 12:00:00"},
  {dt: "2019-11-30 6:00:00"}
]

My goal is to extract and display only the dates with the time set to 12:00:00.

Answer №1

If you want to filter date objects in JavaScript based on specific time criteria, you can employ the array filter function. Start by converting the date string to an internal date representation, and then check for the desired hour, minutes, and seconds.

const datesArray = [
  {dt: "2019-11-29 12:00:00"},
  {dt: "2019-11-29 3:00:00"},
  {dt: "2019-11-29 6:00:00"},
  {dt: "2019-11-30 12:00:00"},
  {dt: "2019-11-30 6:00:00"}
];

const filteredDates = datesArray.filter((dateObj) => {
  const convertedDate = new Date(dateObj.dt);
  return convertedDate.getHours() === 12 && convertedDate.getMinutes() === 0 && convertedDate.getSeconds() === 0;
});
console.info(filteredDates);

Answer №2

Here is a function you can try out. It currently compares hours, but you can add an additional level of if else to compare minutes and seconds as well.

const arr = [{dt: '2019-11-29 12:00:00'},{dt: '2019-11-29 3:0$.00:00'},{dt: '2019-11-30 12:00:00'},{dt: '2019-11-30 6:00:00'}];
console.log('without filter ===',arr)

let filteredArr = [];

for(let i = 0; i < arr.length; i++){
  let dt = new Date(arr[i].dt);
  console.log(dt);
  let hour = dt.getHours()
  let min = dt.getMinutes();
  let sec = dt.getSeconds();
  if(hour <= 12){
    filteredArr.push(arr[i]);
  }
}

console.log('filtered arr ==',filteredArr)

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

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

What is the best way to add up the attributes of objects within an array and save the total to the main

I have a collection of objects, illustrated here: var obj = { "ABC" : { "name" : "ABC", "budget" : 0, "expense" : 0, "ledgers" : [{ "Actual1920": 10, "Budget1920": 20, }, { "Actual1920": 10, ...

I am encountering the error 'user.matchPassword is not a function' while making a call to my API using bcryptjs in my Node.js and Express application. Can someone help me understand why

const checkUserAuth = asyncHandler( async (req,res)=>{ const { email , password } = req.body; const foundUser = User.findOne({email}); if(foundUser && (await foundUser.verifyPassword(password))){ generate ...

Enhancing the "click-to-pause" feature with jQuery Cycle

Is it possible to delay the click-to-pause feature on my slideshow until after the first slide transition? Currently, the slideshow becomes clickable as soon as the DOM is ready, which is too early for my liking. Here is a simplified version of my current ...

When a const variable is declared within the composition-api setup(), it remains unchanged unless redeclared within the function scope

Being primarily a back-end developer, the front-end side of things is still relatively new to me. I'm aware that there are concepts in this domain that I haven't fully grasped yet, and despite my efforts, I'm unable to resolve a particular i ...

Using default value in PHP and JavaScript for a select dropdown

I have an array of cities stored in associative arrays using PHP. I am utilizing JavaScript's "on change" event to capture the value of each item. In the future, I am considering implementing geolocation for setting a default item. Here are my arrays ...

Warning: Unhandled promise rejection - Type error encountered when trying to access property

While working on a simple login validation, I encountered an issue when deliberately inputting an incorrect email in the login post method via postman. UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'password' of null at C:&b ...

Solidjs: Implementing a Map in createStore does not trigger updates upon changes

As a beginner in solidjs, I might have missed something important. In the code snippet below, I am trying to understand an issue: const [state, setState] = createStore({ items: new Map() }); // e.g. Map<number, string> In a component, suppose I want ...

Every page on Nextjs displaying identical content across all routes

I recently deployed a Next.js app using docker on AWS infrastructure. While the index page (/) loads correctly, I've noticed that the content of the index is also being loaded for every other route, including api routes, as well as the JavaScript and ...

Using the excel.js module in conjunction with node.js to create distinct columns within a header row

I am facing an issue with Excel.js while trying to add a header row to a CSV file. It seems that all the columns in the row are getting merged into one cell instead of staying separate. Does anyone know how to properly separate the columns? https://i.sst ...

How does one distinguish between the uses of "any" and "any[ ]"?

Exploring the Difference Between any and any[ ] An Illustrative Example (Functioning as Expected) variable1: any; variable2: any[]; this.variable1 = this.variable2; Another Example (Also Functioning as Intended) variable1: any; v ...

How can I use Node.js Express to upload files with Multer?

I am facing an issue while trying to upload a file image using multer in express. The file gets successfully uploaded to the directory, but the name of the file is not being saved in the database. I am utilizing mongodb with express and currently, the file ...

Error Encountered: RSA Key Pairs Invalid Signature for JSON Web Token (JWT)

I am facing an issue with my Node.js application (version 20.5.1) regarding the verification of JSON Web Tokens (JWT) using RSA key pairs. The specific error message I am encountering is: [16:39:56.959] FATAL (26460): invalid signature err: { "type& ...

Directing JSON POST Request Data to View/Controller in a Node.js Application

Currently, I am working on a project hosted on a local server at http://localhost:3000/. This server receives a post request from another server in the following manner: return requestLib.post({ url: 'http://localhost:3000/test', timeout ...

How to Add Functionality to Angular Apps Without Defining a Route

One unique aspect of my website is the navigation bar. It appears on some pages but not others, so I've created a controller specifically for it. Here's how the navigation bar markup looks: <html ng-app="myApp"> <head> <title& ...

Error: useRef in TypeScript - cannot be assigned to LegacyRef<HTMLDivElement> type

Struggling to implement useRef in TypeScript and facing challenges. When using my RefObject, I need to access its property current like so: node.current. I've experimented with the following approaches: const node: RefObject<HTMLElement> = us ...

Error: The AWS amplify codegen is unable to locate any exported members within the Namespace API

Using AWS resources in my web app, such as a Cognito user pool and an AppSync GraphQL API, requires careful maintenance in a separate project. When modifications are needed, I rely on the amplify command to delete and re-import these resources: $ amplify r ...

An issue has arisen with AngularJS and Twitter Bootstrap, displaying an error message stating that the function element.focus

I recently implemented the angularjs twitter bootstrap datepicker and everything seemed to be working smoothly. However, I encountered an error when trying to click on the text box for the popup datepicker. This issue has left me puzzled as I am still new ...

What is the best way to determine if an object is empty?

I have an array object that I need to check for emptiness. const sampleData = { test:[], test2:[], test1:["can"] } This is the code I'm using to check for emptiness: const dataObject = Object.values(sampleData) console.log(d ...

After consolidating buffer geometries, adjusting the transparency/opacity of the shapes is not an option for me

I've been working on a model with multiple boxes and trying to optimize draw calls by using buffer geometry merger. However, I'm facing an issue where I can't change the opacity of geometries after merging. Here are the things I've tri ...