0

I have looked through other asked questions but havn't found the issue with my code exactly. I am trying to find the newer of 2 dates, and i have split the DD,MM YY,HH,MM,SS into variables so i can do the following and compare

    var bool = false
   if (year1 <= year2)
       if (month1 <= month2)
           if (day1 <= day2)
               if (hours1 <= hours2)
                   if (minutes1 <= minutes2)
                       if (seconds1 <= seconds2)
                           bool = true;
 return bool;

However, I still run into issue if for example the first date is less in Day month and year and hour, but greater in minutes and seconds

ex: if time 1 is 18/7/2016 15:16:4 and time 2 is 19/7/2016 18:14:59

it would result in a false even though time 2 is newer, it just the seconds thats an issue. can this be fixed by else ?

user3676224
  • 863
  • 2
  • 11
  • 25
  • 1
    Why do not do just: `if (year1 <= year2 && month1 <= month2 && day1 <= day2 && hours1 <= hours2 && minutes1 <= minutes2 && seconds1 <= seconds2) { bool = true; }`? – vaso123 Aug 18 '16 at 15:18
  • Why split the date in fields to begin with, rather than using the native comparison operators on `Date` objects? – Aaron Aug 18 '16 at 15:23
  • Possible duplicate of [Compare two dates with JavaScript](http://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – Aaron Aug 18 '16 at 15:23
  • initially i started with that, but in favour of optimization i thought the way i did with multiple if's might better? – user3676224 Aug 18 '16 at 15:24
  • This is premature optimization. Don't go out of your way to optimize until you need it : the time you might gain in computation speed might be shadowed by the time you might loss in maintaining more complex code. – Aaron Aug 18 '16 at 15:26
  • "in favour of optimization"... so all of the logic to extract out different parts of the date and create 12 variables and use 6 comparison operators is more "optimized" than creating 2 date objects, calling getTime() on each of them, and doing a single comparison? – mhodges Aug 18 '16 at 15:29
  • @mhodges—parsing a string to date is 2 lines of code, the date comparison (no need for *getTime*) is one. – RobG Aug 18 '16 at 22:32

2 Answers2

1

For your question: I am trying to find the newer of 2 dates

I can suggest to use getTime() function.

Will be able to compare time by ticks.

Let's consider you have date1 and date2. date1 is 2015-06-10 15:20:30 and date2 is 2016-06-10 16:30:50

date1.getTime() will be smaller than date2.getTime()

date1 Human time (GMT): Wed, 10 Jun 2015 15:20:03 GMT Epoch timestamp: 1433949603 Timestamp in milliseconds: 1433949603000

date2 Human time (GMT): Fri, 10 Jun 2016 16:30:50 GMT Epoch timestamp: 1465576250 Timestamp in milliseconds: 1465576250000

example here

convertor here


Update: Bellow is an example of function:

// returns true if date1 is newer than date2 and false viceversa
function compareForNewer(date1, date2) {
    return date1.getTime() > date2.getTime();
}

Or, you can return always the newer date. As follows:

// returns the newer date
function getNewer(date1, date2) {
    return date1.getTime() > date2.getTime() ? date1 : date2;
}

Hope it will help you. Enjoy!

mihai
  • 2,746
  • 3
  • 35
  • 56
  • @user3676224 I added examples of functions ;) Good luck! – mihai Aug 18 '16 at 15:33
  • There is no need for *getTime*, `date1 > date2` is sufficient since the `>` operator coerces the arguments to Number, and that returns the Date's internal time value, the same as *getTime* does. – RobG Aug 18 '16 at 22:29
0

There are many answers here to questions about parsing, the bottom line is that you can write a bespoke function in a few lines, but likely it's better to get a small parsing and formatting library to do the job. There are plenty of those, such as moment.js, date.js and fecha.js.

For example, using fecha.js and assuming an input format like 18/7/2016 15:16:40 that should be treated as local, you'd do a getEarliest function something like:

/* Convert args to Dates, return earliest as a Date
** or first as a date if they are equal.
** requires fecha.js https://github.com/taylorhakes/fecha
**
** @param {string} dateStr0 - date string in DD/MM/YYYY hh:mm:ss format
** @param {string} dateStr1 - date string in DD/MM/YYYY hh:mm:ss format
** @returns {Date} earliest of dateStr0 and dateStr1 or dateStr0 if equal
*/
function getEarliest(dateStr0, dateStr1) {
  var d0 = fecha.parse(dateStr0, 'DD/MM/YYYY hh:mm:ss');
  var d1 = fecha.parse(dateStr1, 'DD/MM/YYYY hh:mm:ss');
  return d1 < d0? d1 : d0; 
}

Without a general parser, you can use a function like the following and use it to replace the parsing bit. You should also test the result of parsing to make sure it created a valid Date:

/* Parse string in format DD/MM/YYYY hh:mm:ss
** @param {string} s - date string in format DD/MM/YYYY hh:mm:ss
** @returns {Date} if values invalid, returns invalid Date
*/
function parseDate(s) {
  var b = s.split(/\D/);
  var d = new Date(b[2], --b[1], b[0], b[3], b[4], b[5]);
  return d && d.getMinutes() == b[4] && d.getDate() == b[0] && d.getMonth() == b[1]? d : new Date(NaN);
}

/* Convert args to Dates, return earliest as a Date
** or first as a date if they are equal.
** If either date is invalid, returns undefined
**
** @param {string} dateStr0 - date string in DD/MM/YYYY hh:mm:ss format
** @param {string} dateStr1 - date string in DD/MM/YYYY hh:mm:ss format
** @returns {Date} earliest of dateStr0 and dateStr1 or 
**                 dateStr0 if equal or
**                 undefined if either is invalid
*/
function getEarliest(dateStr0, dateStr1) {
  var d0 = parseDate(dateStr0);
  var d1 = parseDate(dateStr1);
  if (isNaN(d0) || isNaN(d1)) return;
  return d1 < d0? d1 : d0; 
}

// Both valid dates
console.log(getEarliest('15/08/2016 15:23:48', '18/08/2016 17:25:08'))

// One date invalid
console.log(parseDate('15/08/2016 15:73:48', '18/08/2016 17:25:08'))
RobG
  • 142,382
  • 31
  • 172
  • 209