Issues with comparing dates

I'm attempting to compare two different dates:

Start Date

Thursday, October 29th, 2015 at 6:00 PM GMT

End Date

Friday, October 30th, 2015 at 12:00 AM GMT

Simply put,

if(end > start)
{
   alert('It works');
}
else
{
   alert('It does not work');
}

However, the condition falls under 'not work'. View my jsfiddle link for reference.

Answer №2

Instead of comparing strings, it is recommended to compare Date objects for more accurate results.

Answer №3

If you are currently comparing strings, consider using the moment() method to compare dates in the moment library. Here's how:

start=moment(start);
end=moment(end);

Check out this demo: http://jsfiddle.net/b7cp91rk/2/

Answer №4

It seems like your intention is to compare the formatted strings, instead of moment or Date objects. If you are using moment.js, it's recommended to compare moment objects using the functions isBefore or isAfter, rather than comparison operators.

Don't forget to provide an input format string during parsing to avoid falling back to the Date constructor and receiving a deprecation warning in your console.

In the example below, I set the variable fmt as the input format and output format for dates. Keep in mind that the RFC822 format used here is not ideal; consider using the ISO8601 format instead.

Additionally, note that I use the moment.utc function to explicitly interpret the input in UTC time, rather than relying on the "GMT" abbreviation, which is crucial.

$(function() {
  var fmt = "ddd, D MMM YYYY HH:mm:ss [GMT]";
  start = moment.utc("Thu, 29 Oct 2015 18:00:00 GMT", fmt);
  end = moment.utc("Fri, 30 Oct 2015 00:00:00 GMT", fmt);
  $('#divLocal').html(start.format(fmt));
  $('#divLocal2').html(end.format(fmt));

  if (end.isAfter(start)) {
    alert("work");
  } else {
    alert("not work");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<div id="divLocal"></div>
<div id='divLocal2'></div>

(Updated jsFiddle)

Answer №5

Give this a shot:

$(function(){
    var start = moment(moment("Thu, 29 Oct 2015 18:00:00 GMT").format("YYYY-MM-DD") + ' ' + "18:00").format("ddd, D MMM YYYY HH:mm:ss") + " GMT";
    var end = moment(moment("Fri, 30 Oct 2015 00:00:00 GMT").format("YYYY-MM-DD") + ' ' + "00:00").format("ddd, D MMM YYYY HH:mm:ss") + " GMT";
    $('#divLocal').html(start);
    $('#divLocal2').html(end);
    if (new Date(end) > new Date(start)) 
    {
    snippet.log("success");
    }
    else
    {
    snippet.log("failure");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
<div id="divLocal"></div>    
<div id='divLocal2'></div>

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

Undefined variable when initializing with ng-init

As a newcomer to AngularJS (and JavaScript in general), I'm currently facing an issue that I could use some help with. Below is the HTML template I am using: <ion-view view-title="Playlists"> <ion-content> <ion-list> ...

What is the best way to extract information from a JavaScript page when the content is identified by a reference?

If you're looking for the website, you can visit . It's primarily in Chinese, but that may not be relevant to the topic at hand. Currently, I am able to extract all the content from this page and now I'm interested in moving on to the next ...

JavaScript's replace() method and the $1 issue

My goal is to develop a script that can identify specific patterns within text and then enclose them in particular tags upon identification. $(".shop_attributes td").each(function () { $(this).html(function(i, html) { return html.replace(/E[0- ...

An unanticipated SyntaxError was encountered while attempting to utilize an Ajax post, specifically in relation

I can't seem to figure out how to troubleshoot an ajax/jquery error. Here is the function I'm working with: var LogIn = { Email: $("#Name").val(), MobileNo: $("#txtMobileNumber").val(), PinCode: '', ...

Trouble displaying Bar Graph in chart.js using PHP

I am facing a challenge with creating a bar graph using chart.js that loads data from a PHP array via ajax. The data is successfully loaded through ajax, as confirmed in the console, but I am unable to display it on the graph. Here's what I see in the ...

Unconventional JavaScript Variable Declaration

While going through some source code, I stumbled upon this peculiar variable declaration that has me a bit confused. let eventsEnabled : ?boolean = null; Can someone explain what exactly this means? You can find the source code here. ...

Tips for stopping ajax requests from automatically following redirects in jQuery

When utilizing the jQuery ajax functions to connect with a web service, I encounter an issue where the server redirects the response to a page with a 200 status code instead of providing a proper status code indicating an error. Unfortunately, I am unable ...

Retrieving text data from the JSON response received from the Aeris API

I am attempting to showcase the word "General" text on the HTML page using data from the API found under details.risk.type. The JSON Response Is As Follows... { "success": true, "error": null, "response": [ ...

How can you use jQuery to remove a class from an element after a specified period of time?

After updating a record in the database, I plan to make modifications using an AJAX request. Once that is done, I will dynamically add a class to the rendered div by utilizing the addClass method. The class being added (we'll refer to it as colored) c ...

What's the Purpose of Using an Arrow Function Instead of Directly Returning a Value in a React Event Handler?

After skimming through various textbooks and blog posts, I've noticed that many explanations on event handlers in React are quite vague... For example, when instructed to write, onChange = {() => setValue(someValue)} onChange = {() => this.pro ...

Issues Persist with Bootstrap Tree View - object passed but no output显示

After going through numerous discussions and solving several issues along the way, I have encountered a major problem where there is no output. As mentioned before, I am utilizing Bootstrap Tree View: To establish the hierarchical structure required for ...

Uncovering targeted information from the current element using $(this) in JavaScript

After running console.log($(this));, I received the following data: https://i.sstatic.net/Wh2p4.png I am looking to combine $(this), access the context, and then move into the attributes. How can I achieve this? ...

Encountering an issue while updating information following the migration to vue-chartjs 4

I recently upgraded from vue-chartjs version 3 to version 4. I successfully migrated my LineChart component by updating the template section and removing the draw method calls. This component is utilized for two separate charts. However, when I close the ...

Typescript - Error in Parsing: Expecting an expression

I am currently working with Vue and TypeScript and have encountered a problem. How can I resolve it? Here is the code snippet in question: private setTitle(systemConfig: any) { const systemConfigParse; let obj; systemConfigParse = JSON.parse(sy ...

Determine if a div contains an svg element with JavaScript

My question involves a div containing a question mark and some SVG elements. Here is the initial setup: <div id="mydiv">?</div> When validating a form submission in my code, I check if the div text contains a question mark like this: const f ...

Displaying Bootstrap alert after a successful jQuery AJAX call

I have been attempting to display an alert on a form once the submission action is completed. Here is my JavaScript function: function submitForm(){ // Initialize Variables With Form Content var nomeCompleto = $("#nomeCompleto").val(); v ...

How to disable form submission using ENTER key in jQuery when alerts are present?

My form contains a text input field. To prevent the form from being submitted when ENTER key is pressed, I used this code snippet: jQuery("#inputTags").keydown(function(event) { if (event.keyCode == '13') { event.preventDefault() ...

What is the best way to transfer information to a different NextJS page?

I want to implement a search input field. The idea is to allow the user to type something into the search bar and then send that input to another page where an API request will be made with the search content. Essentially, when the user types "something" ...

jQuery tip: prevent redundancy in your code by using fadeOut() efficiently

One common issue I encounter is: I have a potentially hidden element I need to perform certain actions on that element If the element is visible, then fade it out using fadeOut() Once the actions are completed, fade the element back in with fadeIn() The ...

Setting up React Router in a nested directory with a flexible route structure

As a newcomer to react router, I am seeking guidance on setting it up in a specific scenario. Imagine we have a PHP application running on 'http://www.example.com'. Within this setup, there is a react application located at 'http://www.examp ...