Find the next nearest date in MM / DD / YYY JavaScript format

I have an array of dates formatted as MM / DD / YYYY. I need to find the next nearest date in the future, starting today. Let's say today was 1/22/2016, then the 2/19/2016 will be back.

2/3/2015
7/5/2015
1/21/2016
2/19/2016
7/1/2016

I tried to make substrings to separate the month, day, year and try to sort based on these values, but there certainly should be a better way.

+6
source share
8 answers

No sorting algorithm needed. You only need to iterate once and find the nearest date that is greater than or equal to today.

PSEUDOKOD

closest <- infinity
foreach date in dates:
    if (date >= now and date < closest) then
        closest <- d
return closest

Javascript

const dates = [
  '2/3/2015',
  '7/5/2015',
  '1/21/2016',
  '2/19/2016',
  '7/1/2016',
  '10/22/2019',
  '08/12/2019',
];

const now = new Date();

let closest = Infinity;

dates.forEach(function(d) {
   const date = new Date(d);

   if (date >= now && (date < new Date(closest) || date < closest)) {
      closest = d;
   }
});

console.log(closest);
Run code

+8
source

, ​​ Moment.JS, .

:

http://momentjs.com/docs/#/displaying/difference/

.

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000

Math.min() .

.min, , :

http://momentjs.com/docs/#/get-set/min/

+4

, . , , . jsbin:

var dates = [
  '2/3/2015',
  '7/5/2015',
  '1/21/2016',
  '2/19/2016',
  '7/1/2016'
];

// parse each string as a Date object and sort them in ascending order
function sortDates(dates) {
  return dates.map(function(date) {
    return new Date(date).getTime();
  }).sort(function(a, b) {
    return a - b;
  });
}

var orderedDates = sortDates(dates);

// remove any dates in the past, and get the first child of the array of remaining dates
var nextDate = orderedDates.filter(function(date) {
  return (Date.now() - date) > 0;
})[0];

, , Date ( , 1/12/2015 12 1 ? JavaScript 12 .

+1

(, , ).

...

, , , , , , .

Frederik.L - , , .

, Date.parse . Date.UTC , OP. , , -.

Date, Date.parse; , , , . array.shift() ;

YYYY-MM-DD

  • ... ( )

var dates = [
    '2/3/2015',
    '7/5/2015',
    '7/1/2016',
    '1/21/2016',
    '2/19/2016'
]; // unsorted garbage dates

var DateList = function( dateList, getDate ) {
    var sortedDates = dateList.sort( function(a, b) {
        return getDate(a) - getDate(b);
    });
    this.next = function() {
        var dt = sortedDates.shift();
        sortedDates.push(dt); // comment to remove cyclical nature
        return dt;
    }
};

// specific implementation parser for this format
var getDisgustingDateFormat = function(dStr) {
    var dParts = dStr.split('/');
    return new Date(Date.UTC(dParts[2],dParts[0],dParts[1]));
};
var dl = new DateList( dates, getDisgustingDateFormat );

dl.next(); // "2/3/2015"
dl.next(); // "7/5/2015"
dl.next(); // "1/21/2016"
dl.next(); // "2/19/2016"
dl.next(); // "7/1/2016"
dl.next(); // "2/3/2015"

, ( )

+1

while, new Date()

var dates = ["2/3/2015","7/5/2015","1/21/2016","2/19/2016","7/1/2016"]
, d = "1/22/2016", n = -1, res = null;

while (++n < dates.length && new Date(dates[n]) < new Date(d));
res = dates[n] || d;
console.log(res)
+1

, .

. , , .

. , null.

- , .

function parseMDY(s) {
  var b = (s || '').split(/\D/);
  return new Date(b[2], b[0]-1, b[1])
}

function getClosestDateToToday(arr) {
  var now = new Date();
  now.setHours(23,59,59);
  return arr.reduce(function (acc, s) {
           var d = parseMDY(s);
           return d < now? acc : (acc && d > parseMDY(acc)? acc : s);
         }, null);
}

var dates = ['2/3/2015', '7/5/2015','1/21/2016',
             '2/19/2016','7/1/2016'];

document.write(getClosestDateToToday(dates));
+1

, for of momentjs:

const getClosestFutureDate = (dates) => {
    if (dates.length === 0) {
        return null;
    }

    let minDiff = 0;
    for (const date of dates) {
        minDiff += minDiff + 30;
        var currentDate = moment(date);
        if (currentDate.isAfter(moment()) && currentDate.diff(moment(), "days") <= minDiff) {
            break;
        }
    }
    return currentDate;
};

now = 2019-08-21

console.log(getClosestFutureDate(["2019-05-07", "2019-06-01", "2019-07-13", "2019-11-09", "2019-11-10", "2019-11-11"])); 

// 2019-11-09

, , Date.

0

In Livescript :

x = 
  * "2/3/2015"
  * "7/5/2015"
  * "1/21/2016"
  * "2/19/2016"
  * "7/1/2016"

sim-unix-ts = (date-str) -> 
  # Simulate unix timestamp like concatenating
  # convert "MM/DD/YYYY" to YYYYMMDD (integer) 
  # so we can simply compare these integers
  [MM, DD, YYYY] = date-str.split "/"
  MM = "0#{MM}".slice -2  # apply zero padding
  DD = "0#{DD}".slice -2  # apply zero padding
  parse-int "#{YYYY}#{MM}#{DD}"

today = sim-unix-ts "2/18/2016"
date-list = [sim-unix-ts(..) for x]

# find next date
next-dates = [.. for date-list when .. > today]
next-date = next-dates.0
next-date-orig = x[date-list.index-of next-date]

alert [next-date, next-date-orig]

.. in Javascript:

var x, simUnixTs, today, dateList, res$, i$, x$, len$, nextDates, y$, nextDate, nextDateOrig;
x = ["2/3/2015", "7/5/2015", "1/21/2016", "2/19/2016", "7/1/2016"];
simUnixTs = function(dateStr){
  var ref$, MM, DD, YYYY;
  ref$ = dateStr.toString().split("/"), MM = ref$[0], DD = ref$[1], YYYY = ref$[2];
  MM = ("0" + MM).slice(-2);
  DD = ("0" + DD).slice(-2);
  return parseInt(YYYY + "" + MM + DD);
};
today = simUnixTs("2/18/2016");
res$ = [];
for (i$ = 0, len$ = x.length; i$ < len$; ++i$) {
  x$ = x[i$];
  res$.push(simUnixTs(x$));
}
dateList = res$;
res$ = [];
for (i$ = 0, len$ = dateList.length; i$ < len$; ++i$) {
  y$ = dateList[i$];
  if (y$ > today) {
    res$.push(y$);
  }
}
nextDates = res$;
nextDate = nextDates[0];
nextDateOrig = x[dateList.indexOf(nextDate)];
alert([nextDate, nextDateOrig]);
-3
source

All Articles