Sorting by Date in JavaScript

My goal is to filter out the elements in an array that have a date (converted from string) greater than a specific date.

_this.downloadData.forEach(_d => _d.LogTime = _d.LogTime.toString());

console.log(_this.downloadData.filter(x=>new Date(x.LogTime) > new Date('3/11/2019 7:29:12 AM')));

However, the filter function always returns zero items.

This is what the array looks like:

[0 … 99]
0:
CPUStat:""
Connectivity:""
DiskStatus:""
HostName:"HOSTname"
LastRebootStatus:null
LogTime:"Mon Mar 11 2019 07:39:12 GMT+0530 (India Standard Time)"

__proto__:
Object

Answer №1

The issue you are facing mainly stems from the date time format not adhering to the ISO 8601 standards. To resolve this, you will need to tidy up the date by extracting the essential parts from your string using

LogTime.substring(4,23) + obj.LogTime.substring(28,33)
. Afterward, employing moment.js (available at https://momentjs.com) is indispensable for handling time in JavaScript.

You can verify the functionality of the code below:

// Sample time array provided
let timeArray = [
  { LogTime:"Mon Mar 11 2019 07:39:12 GMT+0530 (India Standard Time)" },
  { LogTime:"Mon Mar 11 2019 08:39:12 GMT+0530 (India Standard Time)" },
  { LogTime:"Mon Mar 11 2019 09:39:12 GMT+0530 (India Standard Time)" },
  { LogTime:"Mon Mar 11 2019 10:39:12 GMT+0530 (India Standard Time)" }
 ],
 format = "MMM MM YYYY HH:mm:ssZ",
    shouldBeAfter = moment('Mar 11 2019 09:00:12+0530', format),
    result,
    filterDateGreaterThan = function (obj){
      let sDate,
          mDate;
      
      sDate = obj.LogTime.substring(4,23) + obj.LogTime.substring(28,33);
      mDate = moment(sDate, format);
      
      return mDate.isAfter(shouldBeAfter);
    };
 result = timeArray.filter(filterDateGreaterThan);
 console.log(result);
<script src="https://momentjs.com/downloads/moment.min.js"></script>

Alternative code implementation without Moment.js:

// Sample time array provided
let timeArray = [
  { LogTime:"Mon Mar 11 2019 07:39:12 GMT+0530 (India Standard Time)" },
  { LogTime:"Mon Mar 11 2019 08:39:12 GMT+0530 (India Standard Time)" },
  { LogTime:"Mon Mar 11 2019 09:39:12 GMT+0530 (India Standard Time)" },
  { LogTime:"Mon Mar 11 2019 10:39:12 GMT+0530 (India Standard Time)" }
 ],
    shouldBeAfter = new Date('Mar 11 2019 09:00:12+0530'),
    result,
    filterDateGreaterThan = function (obj){
      let sDate,
          date;
      
      sDate = obj.LogTime.substring(4,23) + obj.LogTime.substring(28,33);
      date = new Date(sDate);
      
      return date.valueOf() > shouldBeAfter.valueOf();
    };
 result = timeArray.filter(filterDateGreaterThan);
 console.log(result);

Answer №2

To resolve the issue, it is important to include a timezone in your input data. Failure to do so will result in your browser defaulting to your local timezone. As an example, if my timezone is PDT, the following scenarios demonstrate the impact:

Without Timezone specified:
input  : 3/11/2019 7:29:12 AM
output : Mon Mar 11 2019 07:29:12 GMT-0700 (Pacific Daylight Time)

With Timezone included:
input  : Mon Mar 11 2019 07:39:12 GMT+0530 (India Standard Time)
output : Sun Mar 10 2019 19:09:12 GMT-0700 (Pacific Daylight Time)

It is noticeable that by adding the timezone information in the input, the unix timestamp aligns with the result.


In managing these situations, I personally rely on Moment Timezone.

Without Timezone provided:
input  : moment.tz("3/11/2019 7:29:12 AM", "Asia/Calcutta").toDate();
output : Mon Mar 11 2019 00:29:12 GMT-0700 (Pacific Daylight Time)

With Timezone given:
input  : moment.tz("Mon Mar 11 2019 07:39:12 GMT+0530 (India Standard Time)", "Asia/Calcutta").toDate();
output : Mon Mar 11 2019 00:39:12 GMT-0700 (Pacific Daylight Time)

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

The code within the then() promise resolver function will always execute, regardless of whether the promise succeeds or

After clicking a button, I trigger a vuex action which returns an axios promise from the store. In my component, I only want to reset form fields when the action is successful. However, currently the form fields are always reset, even if the promise fails. ...

Node js server for world's warm greetings

I have been attempting to utilize Node.js for hosting a web server on a dedicated PC, but unfortunately I am unable to access it from anywhere outside of my local network. After researching online, the general consensus is that all I need to do is enter t ...

Service error: The function of "method" is not valid

In one of my Angular 2 applications, I have a class that contains numerous methods for managing authentication. One particular method is responsible for handling errors thrown by the angular/http module. For example, if a response returns a status code o ...

The code functions properly on localhost, but encounters an issue on the live site, resulting in an Uncaught SyntaxError: Unexpected token '<' in JSON at

Can anyone help me understand what this error message means? While testing the script (paypal php virtual terminal) on my localhost, everything works perfectly. However, when I transfer the files to my web server, the jquery/json seems to freeze. index.p ...

Using Ajax.Updater to run JavaScript code

I've tried numerous online tutorials and examples, but haven't had much success... I'm looking to execute JavaScript from an HTML Response in Ajax. Here's my code snippet: <script src="prototype.js" type="text/javascript"></ ...

Best practices for correctly parsing a date in UTC format using the date-fns library

My log file contains timestamps in a non-ISO format: 2020-12-03 08:30:00 2020-12-03 08:40:00 ... The timestamps are in UTC, as per the log provider's documentation. I am attempting to parse them using date-fns: const toParse = "2020-12-03 08:40 ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

What is the process for importing a file with an .mts extension in a CJS-first project?

Here's a snippet from a fetchin.mts file: import type { RequestInfo, RequestInit, Response } from "node-fetch"; const importDynamic = new Function("modulePath", "return import(modulePath);") export async function fetch(u ...

Wildcard routes for publicly accessible files

I have a collection of "widgets" with both client and server-side .coffee files (client representing Backbone.js model/view and server corresponding to ExpressJS routes), all organized within the main project directory: my-node-expressjs3-project/ src/ ...

Tips for utilizing the "this" keyword in TypeScript

As a newcomer to TypeScript, I am seeking assistance on how to access the login service within the authenticate function. Despite using the 'this' keyword to retrieve the login service, it seems ineffective. Additionally, I find myself puzzled by ...

Can someone provide guidance on utilizing the map function to iterate through intricate components in TypeScript?

I am facing a challenge while trying to iterate through a complex object containing 'inner objects'. When using the map function, I can only access one level below. How can I utilize map and TypeScript to loop through multiple levels below? Whene ...

Leveraging Mongodb's aggregate feature to calculate the overall quantity of a specific product that has been ordered across all

Recently delving into the realm of javascript, I am currently tackling a dashboard project that requires displaying the total quantity of each product ordered. Although I have successfully defined a variable 'qty' to represent the quantity of an ...

Is there a quicker method than using document.getElementById('element-id').innerHTML to retrieve content?

Currently, I am developing a user-friendly step-by-step wizard for my website to gather information about custom orders. Utilizing JavaScript, I have been tasked with updating the content of each "page" using the document.getElementById('element-id&ap ...

Tips for transforming a nested array of arrays into a string separated by commas

Currently, I have an object that contains 2 nested arrays. Both of these arrays are array of arrays and I am looking to combine their values into a comma-separated string. I am exploring options in JavaScript, jQuery, or linq.js to accomplish this task. Wh ...

What is the mechanism that guides a reverse while loop to determine its endpoint in JavaScript?

Lately in my exploration of JavaScript, I've discovered that reverse while loops are more efficient. They are often written in this manner: var i = someArray.length; while (i--) { console.log(someArray[i]); } I decided to test it out and noticed ...

Loading all images in advance of the slideshow

Looking to put together a slideshow with around 30-40 images. Want to make sure all the images are loaded before running the slideshow. What's the best way to achieve this? I only want to start the slideshow once everything is fully loaded. ...

Styling with CSS: Using a Base64 Encoded Image in the Background URL

Can a Base64 encoded image be loaded as a background image URL without exposing the actual encoded string in the page source? For example, if a Node API is used to GET request at "/image", it returns the serialized Base64 data. res.json("da ...

Facing a challenge with displaying an angularjs template within a popover

I am having trouble displaying custom HTML content in a popover when clicking on my "View" link. Although other content is rendering correctly, such as one with an ng-repeat inside it, my custom directive does not seem to be processed and displayed properl ...

Sending data with a post request using Ajax in ASP.NET MVC 3

Hey everyone, I'm working on an ajax login call. I'm serializing the form data and sending it to the server to get a redirect URL link. However, I'm running into an issue where my URL after the post ends up looking like http://localhost:508 ...

Having trouble with @babel/plugin-proposal-optional-chaining in Vue.js <script> tag

While working on my vue/vuetify project and attempting to implement optional chaining, I consistently run into an error: ./src/App.vue?vue&type=script&lang=ts& (./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??v ...