d.rodriguez
d.rodriguez

Reputation: 319

Comparing two date values (as string) in javascript

I have a table of 'dates created' and this column is sort-able by ascending and descending order which I'm using Protractor/Jasmine in JavaScript to perform my tests.

Currently I was doing the following, which works, but I wasn't dealing with any dates that were created in the AM and then found my errors.

element.all(by.css('.ui-datatable-data > tr > td:nth-of-type(' + td + ')')).then(function (elements) {
        for (i = 0; i < elements.length; i++) {
            (function (index) {
                elements[index].getText().then(function (text1) {
                    if (index != elements.length - 1) {
                        elements[index + 1].getText().then(function (text2) {
                            if (text2 != undefined && text1 != "") {                                
                                if (order == 'ascending') {
                                    if (text1 < text2 || text1 == text2) {
                                        expect(true).toBeTruthy();
                                    }
                                    else {
                                        expect(text1 + ' was not less than ' + text2).toBe(false);
                                    }
                                }
                                else if (order == 'descending') {
                                    if (text1 > text2 || text1 == text2) {
                                        expect(true).toBeTruthy();
                                    }
                                    else {
                                        expect('text 1:' + text1 + '. Was not greater than:' + text2 + '.').toBe(false);
                                    }
                                }
                            }
                        });
                    }
                });
            })(i);
        }
    });

I searched a little and found out that this method via javascript compares a string character by character. So in the example as follows:

Sep 6, 2016, 5:17:16 PM
Sep 7, 2016, 12:42:44 PM

The first date is less than the second date and my test would pass with the above method.

However in this example:
Sep 6, 2016, 5:17:16 PM
Sep 7, 2016, 12:42:44 AM

The first date is still less than the second date but once it gets to 'is P < A' it fails.

Similarly:
Sep 6, 2016, 5:17:16 PM
Sep 7, 2016, 2:42:44 PM

The first date is yet again less than the second but gets to 'is 5 < 2' and fails.

Is there a smarter/easier way to accomplish this? Or am I just really missing something here.

Upvotes: 0

Views: 7658

Answers (1)

VladNeacsu
VladNeacsu

Reputation: 1288

The date object will do exactly what you expect: Date Object

A small example using your sample data:

var date = new Date("Sep 6, 2016, 5:17:16 PM ");

var date2 = new Date("Sep 7, 2016, 12:42:44 AM");

console.log(date < date2); // true

Upvotes: 4

Related Questions