Find the next closest date in MM/DD/YYY format JavaScript
I have an array of dates formatted as MM/DD/YYYY. I need to find the next closest date in the future starting from today. Say today was 1/22/2016 then 2/19/2016 would return.
2/3/2015
7/5/2015
1/21/2016
2/19/2016
7/1/2016
I've tried doing substrings to get the month, day, year separate and attempting a sort based off those values but surely there has to be a better way.
javascript arrays sorting date
add a comment |
I have an array of dates formatted as MM/DD/YYYY. I need to find the next closest date in the future starting from today. Say today was 1/22/2016 then 2/19/2016 would return.
2/3/2015
7/5/2015
1/21/2016
2/19/2016
7/1/2016
I've tried doing substrings to get the month, day, year separate and attempting a sort based off those values but surely there has to be a better way.
javascript arrays sorting date
Do you only need the very closest date or many of them? Since many solutions uses sorting algorithms and assuming this.
– Frederik.L
May 29 '16 at 2:00
1
All the answers here suggest parsing the strings with the Date constructor. Don't do that. Manually parse strings (a library can help but isn't necessary).
– RobG
May 29 '16 at 9:02
@RobG my answer does not suggest parsing strings with date constructor; it suggests altering the format, and using built-in Date.parse
– MrMesees
May 29 '16 at 12:40
1
@MrMesees—ok, then most of the answers. ;-)
– RobG
May 29 '16 at 22:59
add a comment |
I have an array of dates formatted as MM/DD/YYYY. I need to find the next closest date in the future starting from today. Say today was 1/22/2016 then 2/19/2016 would return.
2/3/2015
7/5/2015
1/21/2016
2/19/2016
7/1/2016
I've tried doing substrings to get the month, day, year separate and attempting a sort based off those values but surely there has to be a better way.
javascript arrays sorting date
I have an array of dates formatted as MM/DD/YYYY. I need to find the next closest date in the future starting from today. Say today was 1/22/2016 then 2/19/2016 would return.
2/3/2015
7/5/2015
1/21/2016
2/19/2016
7/1/2016
I've tried doing substrings to get the month, day, year separate and attempting a sort based off those values but surely there has to be a better way.
javascript arrays sorting date
javascript arrays sorting date
asked May 29 '16 at 0:50
MahoreLeeMahoreLee
42212
42212
Do you only need the very closest date or many of them? Since many solutions uses sorting algorithms and assuming this.
– Frederik.L
May 29 '16 at 2:00
1
All the answers here suggest parsing the strings with the Date constructor. Don't do that. Manually parse strings (a library can help but isn't necessary).
– RobG
May 29 '16 at 9:02
@RobG my answer does not suggest parsing strings with date constructor; it suggests altering the format, and using built-in Date.parse
– MrMesees
May 29 '16 at 12:40
1
@MrMesees—ok, then most of the answers. ;-)
– RobG
May 29 '16 at 22:59
add a comment |
Do you only need the very closest date or many of them? Since many solutions uses sorting algorithms and assuming this.
– Frederik.L
May 29 '16 at 2:00
1
All the answers here suggest parsing the strings with the Date constructor. Don't do that. Manually parse strings (a library can help but isn't necessary).
– RobG
May 29 '16 at 9:02
@RobG my answer does not suggest parsing strings with date constructor; it suggests altering the format, and using built-in Date.parse
– MrMesees
May 29 '16 at 12:40
1
@MrMesees—ok, then most of the answers. ;-)
– RobG
May 29 '16 at 22:59
Do you only need the very closest date or many of them? Since many solutions uses sorting algorithms and assuming this.
– Frederik.L
May 29 '16 at 2:00
Do you only need the very closest date or many of them? Since many solutions uses sorting algorithms and assuming this.
– Frederik.L
May 29 '16 at 2:00
1
1
All the answers here suggest parsing the strings with the Date constructor. Don't do that. Manually parse strings (a library can help but isn't necessary).
– RobG
May 29 '16 at 9:02
All the answers here suggest parsing the strings with the Date constructor. Don't do that. Manually parse strings (a library can help but isn't necessary).
– RobG
May 29 '16 at 9:02
@RobG my answer does not suggest parsing strings with date constructor; it suggests altering the format, and using built-in Date.parse
– MrMesees
May 29 '16 at 12:40
@RobG my answer does not suggest parsing strings with date constructor; it suggests altering the format, and using built-in Date.parse
– MrMesees
May 29 '16 at 12:40
1
1
@MrMesees—ok, then most of the answers. ;-)
– RobG
May 29 '16 at 22:59
@MrMesees—ok, then most of the answers. ;-)
– RobG
May 29 '16 at 22:59
add a comment |
7 Answers
7
active
oldest
votes
There is no need for a sorting algorithm. You only need to iterate once and find the closest date that is greater or equals today.
Pseudocode
closest <- infinity
foreach date in dates:
if (date >= now and date < closest) then
closest <- d
return closest
JavaScript
var dates = [
'2/3/2015',
'7/5/2015',
'1/21/2016',
'2/19/2016',
'7/1/2016'
];
var now = new Date();
var closest = Infinity;
dates.forEach(function(d)
var date = new Date(d);
if (date >= now && date < closest)
closest = d;
);
console.log(closest);
I Like this, but I think it's processing heavy. Each new date requires a loop over every single date, so for this reason I prefer my answer, but your answer reads very well and I can see the rationale.
– MrMesees
May 29 '16 at 1:42
@MrMesees Sorting an array comes at an heavier price than a single iteration over it. Since the OP didn't mention that he wants to get a sorted array, I didn't see a need to sort it. In fact, he said that he needs "the next closest date", not all of them.
– Frederik.L
May 29 '16 at 1:48
Please consider that having a list will generally mean you'll want to do more than one thing with that list. I'm not trying to nit-pick, as I've said I really like your code, it's just not IMHO the best fit for this problem, so I thought I'd reach out and suggest areas for improvement; I'd welcome the same for my answer
– MrMesees
May 29 '16 at 1:56
What happens generally still isn't what the OP asked for... or at least he didn't say he wanted that. I'll try to clear that out. I think that an unwanted sorting is a bad idea since you add unnecessary complexity.
– Frederik.L
May 29 '16 at 2:02
add a comment |
Personally I would use a library such as the very good Moment.JS library, to handle all the horrible complexity of dates.
It has a difference method:
http://momentjs.com/docs/#/displaying/difference/
e.g.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
It would then be trivial to Math.min() the differences of each date in your list.
There's also a moment.min, which might shortcut this entirely, if all your dates are in the future already:
http://momentjs.com/docs/#/get-set/min/
add a comment |
A naïve implementation would be to parse each date as a string and sort them in ascending order. Then, remove any dates that are in the past, and get the first child of the array of remaining dates. See this jsbin example:
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];
Keep in mind that this depends on the format of the date string that you pass to the Date
object (in other words, is 1/12/2015
January 12th, or December 1st? JavaScript will parse it as January 12th.
I'd suggest skipping out on the map as it is destructive to the horrible date format used.
– MrMesees
May 29 '16 at 1:44
@MrMesees thanks for your comment, can you elaborate what you mean a little bit?
– Josh Beam
May 29 '16 at 1:45
So if you do not use the map function, you can still filter, and simply parse the dates twice (see my answer)
– MrMesees
May 29 '16 at 1:46
add a comment |
You can use while
loop, 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)
add a comment |
Lots of answers, one more can't hurt.
Date strings should always be manually parsed. A library can help, but if you only have a single format, a simple function is all that's required.
The following uses reduce to loop over the array of dates and finds the closest future date. If no date is in the future, it returns null.
The returned value is the string from the array, not a Date.
function parseMDY(s)
var b = (s
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));
"Say today was 1/22/2016 then 2/19/2016 would return"
– guest271314
May 29 '16 at 14:03
add a comment |
This really depends upon your dates and data structures (the ones shown in original example are not so great for me).
From the other answers...
To take the example from Josh, you could also keep a pointer to which date you are using, or simply shift off of a sorted queue of dates to make it work, but it's really adding noise to your code, disrupting the purpose.
Frederik.L answer is really beautiful code, but it would still have to be executed multiple times, so I cannot recommend it.
Feedback warning
I've been given feedback in comments that Date.parse can behave inconsistently. I'll move to passing a date parsing callback function, and demonstrate Date.UTC
usage in the callback for OP-specific date format. Please be careful when defining your own callbacks, and please do not copy-paste.
Suggestion
I'd suggest utilizing Date functions i.e. Date.parse; but also try where possible to get data sources sorted without needing application-level sorting. Then you can store-once and step through the array using array.shift()
or similar;
Ideally also YYYY-MM-DD
- Four-Digit Year
- Two-Digit Month
- Two-Digit Day
- ... (continue from least occurring to most occurring)
sample code
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 );
Usage
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"
Hope this helps (Updated for clarity)
new Date(string)
andnew Date(Date.parse(string))
will return identical results as they are functionally equivalent. Strings should never be parsed using either.
– RobG
May 29 '16 at 8:57
I agree the format given is a poor choice, but if OP were to switch to YYYY-MM-DD as I've suggested I'm sure there would be no issues
– MrMesees
May 29 '16 at 14:47
1
My comment isn't about the format. YYYY-MM-DD is not parsed correctly (i.e. per ECMA-262) by all browsers in use. Some parse it as UTC, some as local, some allow out of range values and some won't parse it at all. ;-)
– RobG
May 29 '16 at 23:03
I've edited my example to accept a user-defined callback and shown use of Date.UTC to parse that date manually with a string split. I've also noted the problem with Date.parse... Maybe one day language devs will make a language without so many bugs and bad decisions.
– MrMesees
May 30 '16 at 4:47
1
Don't hold your breath. Given the opportunity to fix at least one aspect of parsing ISO 8601 formatted dates, TC39 failed miserably. See TC39:Date Time String Format: default time zone difference from ES5 not web-compatible #87.
– RobG
May 30 '16 at 5:20
|
show 2 more comments
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]);
Because it's fun :) But stackoverflow is such a strange place that you may get a down vote or may be questioned even though your code works as intended and might help the OP or someone else in some way...
– ceremcem
May 29 '16 at 4:47
1
@MrMesees—what existing Date function functionality is that?
– RobG
May 29 '16 at 8:54
@RobG I was not aware of problems inDate.parse
at the time of the comment, it's been removed. I still think that this is not very friendly code example.
– MrMesees
May 30 '16 at 4:51
@ceremcem I did not down vote your answer since other people did enough yet, but I can explain why it got down votes and why I usually down vote answers like this on SO. Fun stuff is cool to write, but painful to read. It's even more painful to edit and maintain. As developers, we must show the community that they should use cleaner code, instead of faster, wobbling code. The exception is made when there is a significant performance issue and the wobbling thing is greatly resolving the issue.
– Frederik.L
May 31 '16 at 6:09
1
@Frederik.L I totally agree about writing cleaner code. Then I totally accept the downvotes. Thank you.
– ceremcem
May 31 '16 at 14:34
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37505117%2ffind-the-next-closest-date-in-mm-dd-yyy-format-javascript%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
There is no need for a sorting algorithm. You only need to iterate once and find the closest date that is greater or equals today.
Pseudocode
closest <- infinity
foreach date in dates:
if (date >= now and date < closest) then
closest <- d
return closest
JavaScript
var dates = [
'2/3/2015',
'7/5/2015',
'1/21/2016',
'2/19/2016',
'7/1/2016'
];
var now = new Date();
var closest = Infinity;
dates.forEach(function(d)
var date = new Date(d);
if (date >= now && date < closest)
closest = d;
);
console.log(closest);
I Like this, but I think it's processing heavy. Each new date requires a loop over every single date, so for this reason I prefer my answer, but your answer reads very well and I can see the rationale.
– MrMesees
May 29 '16 at 1:42
@MrMesees Sorting an array comes at an heavier price than a single iteration over it. Since the OP didn't mention that he wants to get a sorted array, I didn't see a need to sort it. In fact, he said that he needs "the next closest date", not all of them.
– Frederik.L
May 29 '16 at 1:48
Please consider that having a list will generally mean you'll want to do more than one thing with that list. I'm not trying to nit-pick, as I've said I really like your code, it's just not IMHO the best fit for this problem, so I thought I'd reach out and suggest areas for improvement; I'd welcome the same for my answer
– MrMesees
May 29 '16 at 1:56
What happens generally still isn't what the OP asked for... or at least he didn't say he wanted that. I'll try to clear that out. I think that an unwanted sorting is a bad idea since you add unnecessary complexity.
– Frederik.L
May 29 '16 at 2:02
add a comment |
There is no need for a sorting algorithm. You only need to iterate once and find the closest date that is greater or equals today.
Pseudocode
closest <- infinity
foreach date in dates:
if (date >= now and date < closest) then
closest <- d
return closest
JavaScript
var dates = [
'2/3/2015',
'7/5/2015',
'1/21/2016',
'2/19/2016',
'7/1/2016'
];
var now = new Date();
var closest = Infinity;
dates.forEach(function(d)
var date = new Date(d);
if (date >= now && date < closest)
closest = d;
);
console.log(closest);
I Like this, but I think it's processing heavy. Each new date requires a loop over every single date, so for this reason I prefer my answer, but your answer reads very well and I can see the rationale.
– MrMesees
May 29 '16 at 1:42
@MrMesees Sorting an array comes at an heavier price than a single iteration over it. Since the OP didn't mention that he wants to get a sorted array, I didn't see a need to sort it. In fact, he said that he needs "the next closest date", not all of them.
– Frederik.L
May 29 '16 at 1:48
Please consider that having a list will generally mean you'll want to do more than one thing with that list. I'm not trying to nit-pick, as I've said I really like your code, it's just not IMHO the best fit for this problem, so I thought I'd reach out and suggest areas for improvement; I'd welcome the same for my answer
– MrMesees
May 29 '16 at 1:56
What happens generally still isn't what the OP asked for... or at least he didn't say he wanted that. I'll try to clear that out. I think that an unwanted sorting is a bad idea since you add unnecessary complexity.
– Frederik.L
May 29 '16 at 2:02
add a comment |
There is no need for a sorting algorithm. You only need to iterate once and find the closest date that is greater or equals today.
Pseudocode
closest <- infinity
foreach date in dates:
if (date >= now and date < closest) then
closest <- d
return closest
JavaScript
var dates = [
'2/3/2015',
'7/5/2015',
'1/21/2016',
'2/19/2016',
'7/1/2016'
];
var now = new Date();
var closest = Infinity;
dates.forEach(function(d)
var date = new Date(d);
if (date >= now && date < closest)
closest = d;
);
console.log(closest);
There is no need for a sorting algorithm. You only need to iterate once and find the closest date that is greater or equals today.
Pseudocode
closest <- infinity
foreach date in dates:
if (date >= now and date < closest) then
closest <- d
return closest
JavaScript
var dates = [
'2/3/2015',
'7/5/2015',
'1/21/2016',
'2/19/2016',
'7/1/2016'
];
var now = new Date();
var closest = Infinity;
dates.forEach(function(d)
var date = new Date(d);
if (date >= now && date < closest)
closest = d;
);
console.log(closest);
var dates = [
'2/3/2015',
'7/5/2015',
'1/21/2016',
'2/19/2016',
'7/1/2016'
];
var now = new Date();
var closest = Infinity;
dates.forEach(function(d)
var date = new Date(d);
if (date >= now && date < closest)
closest = d;
);
console.log(closest);
var dates = [
'2/3/2015',
'7/5/2015',
'1/21/2016',
'2/19/2016',
'7/1/2016'
];
var now = new Date();
var closest = Infinity;
dates.forEach(function(d)
var date = new Date(d);
if (date >= now && date < closest)
closest = d;
);
console.log(closest);
edited May 29 '16 at 1:35
answered May 29 '16 at 1:30
Frederik.LFrederik.L
4,42411735
4,42411735
I Like this, but I think it's processing heavy. Each new date requires a loop over every single date, so for this reason I prefer my answer, but your answer reads very well and I can see the rationale.
– MrMesees
May 29 '16 at 1:42
@MrMesees Sorting an array comes at an heavier price than a single iteration over it. Since the OP didn't mention that he wants to get a sorted array, I didn't see a need to sort it. In fact, he said that he needs "the next closest date", not all of them.
– Frederik.L
May 29 '16 at 1:48
Please consider that having a list will generally mean you'll want to do more than one thing with that list. I'm not trying to nit-pick, as I've said I really like your code, it's just not IMHO the best fit for this problem, so I thought I'd reach out and suggest areas for improvement; I'd welcome the same for my answer
– MrMesees
May 29 '16 at 1:56
What happens generally still isn't what the OP asked for... or at least he didn't say he wanted that. I'll try to clear that out. I think that an unwanted sorting is a bad idea since you add unnecessary complexity.
– Frederik.L
May 29 '16 at 2:02
add a comment |
I Like this, but I think it's processing heavy. Each new date requires a loop over every single date, so for this reason I prefer my answer, but your answer reads very well and I can see the rationale.
– MrMesees
May 29 '16 at 1:42
@MrMesees Sorting an array comes at an heavier price than a single iteration over it. Since the OP didn't mention that he wants to get a sorted array, I didn't see a need to sort it. In fact, he said that he needs "the next closest date", not all of them.
– Frederik.L
May 29 '16 at 1:48
Please consider that having a list will generally mean you'll want to do more than one thing with that list. I'm not trying to nit-pick, as I've said I really like your code, it's just not IMHO the best fit for this problem, so I thought I'd reach out and suggest areas for improvement; I'd welcome the same for my answer
– MrMesees
May 29 '16 at 1:56
What happens generally still isn't what the OP asked for... or at least he didn't say he wanted that. I'll try to clear that out. I think that an unwanted sorting is a bad idea since you add unnecessary complexity.
– Frederik.L
May 29 '16 at 2:02
I Like this, but I think it's processing heavy. Each new date requires a loop over every single date, so for this reason I prefer my answer, but your answer reads very well and I can see the rationale.
– MrMesees
May 29 '16 at 1:42
I Like this, but I think it's processing heavy. Each new date requires a loop over every single date, so for this reason I prefer my answer, but your answer reads very well and I can see the rationale.
– MrMesees
May 29 '16 at 1:42
@MrMesees Sorting an array comes at an heavier price than a single iteration over it. Since the OP didn't mention that he wants to get a sorted array, I didn't see a need to sort it. In fact, he said that he needs "the next closest date", not all of them.
– Frederik.L
May 29 '16 at 1:48
@MrMesees Sorting an array comes at an heavier price than a single iteration over it. Since the OP didn't mention that he wants to get a sorted array, I didn't see a need to sort it. In fact, he said that he needs "the next closest date", not all of them.
– Frederik.L
May 29 '16 at 1:48
Please consider that having a list will generally mean you'll want to do more than one thing with that list. I'm not trying to nit-pick, as I've said I really like your code, it's just not IMHO the best fit for this problem, so I thought I'd reach out and suggest areas for improvement; I'd welcome the same for my answer
– MrMesees
May 29 '16 at 1:56
Please consider that having a list will generally mean you'll want to do more than one thing with that list. I'm not trying to nit-pick, as I've said I really like your code, it's just not IMHO the best fit for this problem, so I thought I'd reach out and suggest areas for improvement; I'd welcome the same for my answer
– MrMesees
May 29 '16 at 1:56
What happens generally still isn't what the OP asked for... or at least he didn't say he wanted that. I'll try to clear that out. I think that an unwanted sorting is a bad idea since you add unnecessary complexity.
– Frederik.L
May 29 '16 at 2:02
What happens generally still isn't what the OP asked for... or at least he didn't say he wanted that. I'll try to clear that out. I think that an unwanted sorting is a bad idea since you add unnecessary complexity.
– Frederik.L
May 29 '16 at 2:02
add a comment |
Personally I would use a library such as the very good Moment.JS library, to handle all the horrible complexity of dates.
It has a difference method:
http://momentjs.com/docs/#/displaying/difference/
e.g.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
It would then be trivial to Math.min() the differences of each date in your list.
There's also a moment.min, which might shortcut this entirely, if all your dates are in the future already:
http://momentjs.com/docs/#/get-set/min/
add a comment |
Personally I would use a library such as the very good Moment.JS library, to handle all the horrible complexity of dates.
It has a difference method:
http://momentjs.com/docs/#/displaying/difference/
e.g.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
It would then be trivial to Math.min() the differences of each date in your list.
There's also a moment.min, which might shortcut this entirely, if all your dates are in the future already:
http://momentjs.com/docs/#/get-set/min/
add a comment |
Personally I would use a library such as the very good Moment.JS library, to handle all the horrible complexity of dates.
It has a difference method:
http://momentjs.com/docs/#/displaying/difference/
e.g.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
It would then be trivial to Math.min() the differences of each date in your list.
There's also a moment.min, which might shortcut this entirely, if all your dates are in the future already:
http://momentjs.com/docs/#/get-set/min/
Personally I would use a library such as the very good Moment.JS library, to handle all the horrible complexity of dates.
It has a difference method:
http://momentjs.com/docs/#/displaying/difference/
e.g.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
It would then be trivial to Math.min() the differences of each date in your list.
There's also a moment.min, which might shortcut this entirely, if all your dates are in the future already:
http://momentjs.com/docs/#/get-set/min/
answered May 29 '16 at 2:27
scipilotscipilot
2,93812135
2,93812135
add a comment |
add a comment |
A naïve implementation would be to parse each date as a string and sort them in ascending order. Then, remove any dates that are in the past, and get the first child of the array of remaining dates. See this jsbin example:
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];
Keep in mind that this depends on the format of the date string that you pass to the Date
object (in other words, is 1/12/2015
January 12th, or December 1st? JavaScript will parse it as January 12th.
I'd suggest skipping out on the map as it is destructive to the horrible date format used.
– MrMesees
May 29 '16 at 1:44
@MrMesees thanks for your comment, can you elaborate what you mean a little bit?
– Josh Beam
May 29 '16 at 1:45
So if you do not use the map function, you can still filter, and simply parse the dates twice (see my answer)
– MrMesees
May 29 '16 at 1:46
add a comment |
A naïve implementation would be to parse each date as a string and sort them in ascending order. Then, remove any dates that are in the past, and get the first child of the array of remaining dates. See this jsbin example:
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];
Keep in mind that this depends on the format of the date string that you pass to the Date
object (in other words, is 1/12/2015
January 12th, or December 1st? JavaScript will parse it as January 12th.
I'd suggest skipping out on the map as it is destructive to the horrible date format used.
– MrMesees
May 29 '16 at 1:44
@MrMesees thanks for your comment, can you elaborate what you mean a little bit?
– Josh Beam
May 29 '16 at 1:45
So if you do not use the map function, you can still filter, and simply parse the dates twice (see my answer)
– MrMesees
May 29 '16 at 1:46
add a comment |
A naïve implementation would be to parse each date as a string and sort them in ascending order. Then, remove any dates that are in the past, and get the first child of the array of remaining dates. See this jsbin example:
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];
Keep in mind that this depends on the format of the date string that you pass to the Date
object (in other words, is 1/12/2015
January 12th, or December 1st? JavaScript will parse it as January 12th.
A naïve implementation would be to parse each date as a string and sort them in ascending order. Then, remove any dates that are in the past, and get the first child of the array of remaining dates. See this jsbin example:
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];
Keep in mind that this depends on the format of the date string that you pass to the Date
object (in other words, is 1/12/2015
January 12th, or December 1st? JavaScript will parse it as January 12th.
answered May 29 '16 at 1:04
Josh BeamJosh Beam
13.8k12255
13.8k12255
I'd suggest skipping out on the map as it is destructive to the horrible date format used.
– MrMesees
May 29 '16 at 1:44
@MrMesees thanks for your comment, can you elaborate what you mean a little bit?
– Josh Beam
May 29 '16 at 1:45
So if you do not use the map function, you can still filter, and simply parse the dates twice (see my answer)
– MrMesees
May 29 '16 at 1:46
add a comment |
I'd suggest skipping out on the map as it is destructive to the horrible date format used.
– MrMesees
May 29 '16 at 1:44
@MrMesees thanks for your comment, can you elaborate what you mean a little bit?
– Josh Beam
May 29 '16 at 1:45
So if you do not use the map function, you can still filter, and simply parse the dates twice (see my answer)
– MrMesees
May 29 '16 at 1:46
I'd suggest skipping out on the map as it is destructive to the horrible date format used.
– MrMesees
May 29 '16 at 1:44
I'd suggest skipping out on the map as it is destructive to the horrible date format used.
– MrMesees
May 29 '16 at 1:44
@MrMesees thanks for your comment, can you elaborate what you mean a little bit?
– Josh Beam
May 29 '16 at 1:45
@MrMesees thanks for your comment, can you elaborate what you mean a little bit?
– Josh Beam
May 29 '16 at 1:45
So if you do not use the map function, you can still filter, and simply parse the dates twice (see my answer)
– MrMesees
May 29 '16 at 1:46
So if you do not use the map function, you can still filter, and simply parse the dates twice (see my answer)
– MrMesees
May 29 '16 at 1:46
add a comment |
You can use while
loop, 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)
add a comment |
You can use while
loop, 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)
add a comment |
You can use while
loop, 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)
You can use while
loop, 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)
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)
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)
edited May 29 '16 at 2:29
answered May 29 '16 at 1:49
guest271314guest271314
1
1
add a comment |
add a comment |
Lots of answers, one more can't hurt.
Date strings should always be manually parsed. A library can help, but if you only have a single format, a simple function is all that's required.
The following uses reduce to loop over the array of dates and finds the closest future date. If no date is in the future, it returns null.
The returned value is the string from the array, not a Date.
function parseMDY(s)
var b = (s
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));
"Say today was 1/22/2016 then 2/19/2016 would return"
– guest271314
May 29 '16 at 14:03
add a comment |
Lots of answers, one more can't hurt.
Date strings should always be manually parsed. A library can help, but if you only have a single format, a simple function is all that's required.
The following uses reduce to loop over the array of dates and finds the closest future date. If no date is in the future, it returns null.
The returned value is the string from the array, not a Date.
function parseMDY(s)
var b = (s
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));
"Say today was 1/22/2016 then 2/19/2016 would return"
– guest271314
May 29 '16 at 14:03
add a comment |
Lots of answers, one more can't hurt.
Date strings should always be manually parsed. A library can help, but if you only have a single format, a simple function is all that's required.
The following uses reduce to loop over the array of dates and finds the closest future date. If no date is in the future, it returns null.
The returned value is the string from the array, not a Date.
function parseMDY(s)
var b = (s
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));
Lots of answers, one more can't hurt.
Date strings should always be manually parsed. A library can help, but if you only have a single format, a simple function is all that's required.
The following uses reduce to loop over the array of dates and finds the closest future date. If no date is in the future, it returns null.
The returned value is the string from the array, not a Date.
function parseMDY(s)
var b = (s
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));
function parseMDY(s)
var b = (s
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));
function parseMDY(s)
var b = (s
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));
answered May 29 '16 at 9:59
RobGRobG
97.7k19106145
97.7k19106145
"Say today was 1/22/2016 then 2/19/2016 would return"
– guest271314
May 29 '16 at 14:03
add a comment |
"Say today was 1/22/2016 then 2/19/2016 would return"
– guest271314
May 29 '16 at 14:03
"Say today was 1/22/2016 then 2/19/2016 would return"
– guest271314
May 29 '16 at 14:03
"Say today was 1/22/2016 then 2/19/2016 would return"
– guest271314
May 29 '16 at 14:03
add a comment |
This really depends upon your dates and data structures (the ones shown in original example are not so great for me).
From the other answers...
To take the example from Josh, you could also keep a pointer to which date you are using, or simply shift off of a sorted queue of dates to make it work, but it's really adding noise to your code, disrupting the purpose.
Frederik.L answer is really beautiful code, but it would still have to be executed multiple times, so I cannot recommend it.
Feedback warning
I've been given feedback in comments that Date.parse can behave inconsistently. I'll move to passing a date parsing callback function, and demonstrate Date.UTC
usage in the callback for OP-specific date format. Please be careful when defining your own callbacks, and please do not copy-paste.
Suggestion
I'd suggest utilizing Date functions i.e. Date.parse; but also try where possible to get data sources sorted without needing application-level sorting. Then you can store-once and step through the array using array.shift()
or similar;
Ideally also YYYY-MM-DD
- Four-Digit Year
- Two-Digit Month
- Two-Digit Day
- ... (continue from least occurring to most occurring)
sample code
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 );
Usage
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"
Hope this helps (Updated for clarity)
new Date(string)
andnew Date(Date.parse(string))
will return identical results as they are functionally equivalent. Strings should never be parsed using either.
– RobG
May 29 '16 at 8:57
I agree the format given is a poor choice, but if OP were to switch to YYYY-MM-DD as I've suggested I'm sure there would be no issues
– MrMesees
May 29 '16 at 14:47
1
My comment isn't about the format. YYYY-MM-DD is not parsed correctly (i.e. per ECMA-262) by all browsers in use. Some parse it as UTC, some as local, some allow out of range values and some won't parse it at all. ;-)
– RobG
May 29 '16 at 23:03
I've edited my example to accept a user-defined callback and shown use of Date.UTC to parse that date manually with a string split. I've also noted the problem with Date.parse... Maybe one day language devs will make a language without so many bugs and bad decisions.
– MrMesees
May 30 '16 at 4:47
1
Don't hold your breath. Given the opportunity to fix at least one aspect of parsing ISO 8601 formatted dates, TC39 failed miserably. See TC39:Date Time String Format: default time zone difference from ES5 not web-compatible #87.
– RobG
May 30 '16 at 5:20
|
show 2 more comments
This really depends upon your dates and data structures (the ones shown in original example are not so great for me).
From the other answers...
To take the example from Josh, you could also keep a pointer to which date you are using, or simply shift off of a sorted queue of dates to make it work, but it's really adding noise to your code, disrupting the purpose.
Frederik.L answer is really beautiful code, but it would still have to be executed multiple times, so I cannot recommend it.
Feedback warning
I've been given feedback in comments that Date.parse can behave inconsistently. I'll move to passing a date parsing callback function, and demonstrate Date.UTC
usage in the callback for OP-specific date format. Please be careful when defining your own callbacks, and please do not copy-paste.
Suggestion
I'd suggest utilizing Date functions i.e. Date.parse; but also try where possible to get data sources sorted without needing application-level sorting. Then you can store-once and step through the array using array.shift()
or similar;
Ideally also YYYY-MM-DD
- Four-Digit Year
- Two-Digit Month
- Two-Digit Day
- ... (continue from least occurring to most occurring)
sample code
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 );
Usage
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"
Hope this helps (Updated for clarity)
new Date(string)
andnew Date(Date.parse(string))
will return identical results as they are functionally equivalent. Strings should never be parsed using either.
– RobG
May 29 '16 at 8:57
I agree the format given is a poor choice, but if OP were to switch to YYYY-MM-DD as I've suggested I'm sure there would be no issues
– MrMesees
May 29 '16 at 14:47
1
My comment isn't about the format. YYYY-MM-DD is not parsed correctly (i.e. per ECMA-262) by all browsers in use. Some parse it as UTC, some as local, some allow out of range values and some won't parse it at all. ;-)
– RobG
May 29 '16 at 23:03
I've edited my example to accept a user-defined callback and shown use of Date.UTC to parse that date manually with a string split. I've also noted the problem with Date.parse... Maybe one day language devs will make a language without so many bugs and bad decisions.
– MrMesees
May 30 '16 at 4:47
1
Don't hold your breath. Given the opportunity to fix at least one aspect of parsing ISO 8601 formatted dates, TC39 failed miserably. See TC39:Date Time String Format: default time zone difference from ES5 not web-compatible #87.
– RobG
May 30 '16 at 5:20
|
show 2 more comments
This really depends upon your dates and data structures (the ones shown in original example are not so great for me).
From the other answers...
To take the example from Josh, you could also keep a pointer to which date you are using, or simply shift off of a sorted queue of dates to make it work, but it's really adding noise to your code, disrupting the purpose.
Frederik.L answer is really beautiful code, but it would still have to be executed multiple times, so I cannot recommend it.
Feedback warning
I've been given feedback in comments that Date.parse can behave inconsistently. I'll move to passing a date parsing callback function, and demonstrate Date.UTC
usage in the callback for OP-specific date format. Please be careful when defining your own callbacks, and please do not copy-paste.
Suggestion
I'd suggest utilizing Date functions i.e. Date.parse; but also try where possible to get data sources sorted without needing application-level sorting. Then you can store-once and step through the array using array.shift()
or similar;
Ideally also YYYY-MM-DD
- Four-Digit Year
- Two-Digit Month
- Two-Digit Day
- ... (continue from least occurring to most occurring)
sample code
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 );
Usage
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"
Hope this helps (Updated for clarity)
This really depends upon your dates and data structures (the ones shown in original example are not so great for me).
From the other answers...
To take the example from Josh, you could also keep a pointer to which date you are using, or simply shift off of a sorted queue of dates to make it work, but it's really adding noise to your code, disrupting the purpose.
Frederik.L answer is really beautiful code, but it would still have to be executed multiple times, so I cannot recommend it.
Feedback warning
I've been given feedback in comments that Date.parse can behave inconsistently. I'll move to passing a date parsing callback function, and demonstrate Date.UTC
usage in the callback for OP-specific date format. Please be careful when defining your own callbacks, and please do not copy-paste.
Suggestion
I'd suggest utilizing Date functions i.e. Date.parse; but also try where possible to get data sources sorted without needing application-level sorting. Then you can store-once and step through the array using array.shift()
or similar;
Ideally also YYYY-MM-DD
- Four-Digit Year
- Two-Digit Month
- Two-Digit Day
- ... (continue from least occurring to most occurring)
sample code
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 );
Usage
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"
Hope this helps (Updated for clarity)
edited May 30 '16 at 5:33
answered May 29 '16 at 1:38
MrMeseesMrMesees
6371217
6371217
new Date(string)
andnew Date(Date.parse(string))
will return identical results as they are functionally equivalent. Strings should never be parsed using either.
– RobG
May 29 '16 at 8:57
I agree the format given is a poor choice, but if OP were to switch to YYYY-MM-DD as I've suggested I'm sure there would be no issues
– MrMesees
May 29 '16 at 14:47
1
My comment isn't about the format. YYYY-MM-DD is not parsed correctly (i.e. per ECMA-262) by all browsers in use. Some parse it as UTC, some as local, some allow out of range values and some won't parse it at all. ;-)
– RobG
May 29 '16 at 23:03
I've edited my example to accept a user-defined callback and shown use of Date.UTC to parse that date manually with a string split. I've also noted the problem with Date.parse... Maybe one day language devs will make a language without so many bugs and bad decisions.
– MrMesees
May 30 '16 at 4:47
1
Don't hold your breath. Given the opportunity to fix at least one aspect of parsing ISO 8601 formatted dates, TC39 failed miserably. See TC39:Date Time String Format: default time zone difference from ES5 not web-compatible #87.
– RobG
May 30 '16 at 5:20
|
show 2 more comments
new Date(string)
andnew Date(Date.parse(string))
will return identical results as they are functionally equivalent. Strings should never be parsed using either.
– RobG
May 29 '16 at 8:57
I agree the format given is a poor choice, but if OP were to switch to YYYY-MM-DD as I've suggested I'm sure there would be no issues
– MrMesees
May 29 '16 at 14:47
1
My comment isn't about the format. YYYY-MM-DD is not parsed correctly (i.e. per ECMA-262) by all browsers in use. Some parse it as UTC, some as local, some allow out of range values and some won't parse it at all. ;-)
– RobG
May 29 '16 at 23:03
I've edited my example to accept a user-defined callback and shown use of Date.UTC to parse that date manually with a string split. I've also noted the problem with Date.parse... Maybe one day language devs will make a language without so many bugs and bad decisions.
– MrMesees
May 30 '16 at 4:47
1
Don't hold your breath. Given the opportunity to fix at least one aspect of parsing ISO 8601 formatted dates, TC39 failed miserably. See TC39:Date Time String Format: default time zone difference from ES5 not web-compatible #87.
– RobG
May 30 '16 at 5:20
new Date(string)
and new Date(Date.parse(string))
will return identical results as they are functionally equivalent. Strings should never be parsed using either.– RobG
May 29 '16 at 8:57
new Date(string)
and new Date(Date.parse(string))
will return identical results as they are functionally equivalent. Strings should never be parsed using either.– RobG
May 29 '16 at 8:57
I agree the format given is a poor choice, but if OP were to switch to YYYY-MM-DD as I've suggested I'm sure there would be no issues
– MrMesees
May 29 '16 at 14:47
I agree the format given is a poor choice, but if OP were to switch to YYYY-MM-DD as I've suggested I'm sure there would be no issues
– MrMesees
May 29 '16 at 14:47
1
1
My comment isn't about the format. YYYY-MM-DD is not parsed correctly (i.e. per ECMA-262) by all browsers in use. Some parse it as UTC, some as local, some allow out of range values and some won't parse it at all. ;-)
– RobG
May 29 '16 at 23:03
My comment isn't about the format. YYYY-MM-DD is not parsed correctly (i.e. per ECMA-262) by all browsers in use. Some parse it as UTC, some as local, some allow out of range values and some won't parse it at all. ;-)
– RobG
May 29 '16 at 23:03
I've edited my example to accept a user-defined callback and shown use of Date.UTC to parse that date manually with a string split. I've also noted the problem with Date.parse... Maybe one day language devs will make a language without so many bugs and bad decisions.
– MrMesees
May 30 '16 at 4:47
I've edited my example to accept a user-defined callback and shown use of Date.UTC to parse that date manually with a string split. I've also noted the problem with Date.parse... Maybe one day language devs will make a language without so many bugs and bad decisions.
– MrMesees
May 30 '16 at 4:47
1
1
Don't hold your breath. Given the opportunity to fix at least one aspect of parsing ISO 8601 formatted dates, TC39 failed miserably. See TC39:Date Time String Format: default time zone difference from ES5 not web-compatible #87.
– RobG
May 30 '16 at 5:20
Don't hold your breath. Given the opportunity to fix at least one aspect of parsing ISO 8601 formatted dates, TC39 failed miserably. See TC39:Date Time String Format: default time zone difference from ES5 not web-compatible #87.
– RobG
May 30 '16 at 5:20
|
show 2 more comments
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]);
Because it's fun :) But stackoverflow is such a strange place that you may get a down vote or may be questioned even though your code works as intended and might help the OP or someone else in some way...
– ceremcem
May 29 '16 at 4:47
1
@MrMesees—what existing Date function functionality is that?
– RobG
May 29 '16 at 8:54
@RobG I was not aware of problems inDate.parse
at the time of the comment, it's been removed. I still think that this is not very friendly code example.
– MrMesees
May 30 '16 at 4:51
@ceremcem I did not down vote your answer since other people did enough yet, but I can explain why it got down votes and why I usually down vote answers like this on SO. Fun stuff is cool to write, but painful to read. It's even more painful to edit and maintain. As developers, we must show the community that they should use cleaner code, instead of faster, wobbling code. The exception is made when there is a significant performance issue and the wobbling thing is greatly resolving the issue.
– Frederik.L
May 31 '16 at 6:09
1
@Frederik.L I totally agree about writing cleaner code. Then I totally accept the downvotes. Thank you.
– ceremcem
May 31 '16 at 14:34
add a comment |
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]);
Because it's fun :) But stackoverflow is such a strange place that you may get a down vote or may be questioned even though your code works as intended and might help the OP or someone else in some way...
– ceremcem
May 29 '16 at 4:47
1
@MrMesees—what existing Date function functionality is that?
– RobG
May 29 '16 at 8:54
@RobG I was not aware of problems inDate.parse
at the time of the comment, it's been removed. I still think that this is not very friendly code example.
– MrMesees
May 30 '16 at 4:51
@ceremcem I did not down vote your answer since other people did enough yet, but I can explain why it got down votes and why I usually down vote answers like this on SO. Fun stuff is cool to write, but painful to read. It's even more painful to edit and maintain. As developers, we must show the community that they should use cleaner code, instead of faster, wobbling code. The exception is made when there is a significant performance issue and the wobbling thing is greatly resolving the issue.
– Frederik.L
May 31 '16 at 6:09
1
@Frederik.L I totally agree about writing cleaner code. Then I totally accept the downvotes. Thank you.
– ceremcem
May 31 '16 at 14:34
add a comment |
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]);
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]);
edited May 31 '16 at 15:12
answered May 29 '16 at 1:36
ceremcemceremcem
1,18721435
1,18721435
Because it's fun :) But stackoverflow is such a strange place that you may get a down vote or may be questioned even though your code works as intended and might help the OP or someone else in some way...
– ceremcem
May 29 '16 at 4:47
1
@MrMesees—what existing Date function functionality is that?
– RobG
May 29 '16 at 8:54
@RobG I was not aware of problems inDate.parse
at the time of the comment, it's been removed. I still think that this is not very friendly code example.
– MrMesees
May 30 '16 at 4:51
@ceremcem I did not down vote your answer since other people did enough yet, but I can explain why it got down votes and why I usually down vote answers like this on SO. Fun stuff is cool to write, but painful to read. It's even more painful to edit and maintain. As developers, we must show the community that they should use cleaner code, instead of faster, wobbling code. The exception is made when there is a significant performance issue and the wobbling thing is greatly resolving the issue.
– Frederik.L
May 31 '16 at 6:09
1
@Frederik.L I totally agree about writing cleaner code. Then I totally accept the downvotes. Thank you.
– ceremcem
May 31 '16 at 14:34
add a comment |
Because it's fun :) But stackoverflow is such a strange place that you may get a down vote or may be questioned even though your code works as intended and might help the OP or someone else in some way...
– ceremcem
May 29 '16 at 4:47
1
@MrMesees—what existing Date function functionality is that?
– RobG
May 29 '16 at 8:54
@RobG I was not aware of problems inDate.parse
at the time of the comment, it's been removed. I still think that this is not very friendly code example.
– MrMesees
May 30 '16 at 4:51
@ceremcem I did not down vote your answer since other people did enough yet, but I can explain why it got down votes and why I usually down vote answers like this on SO. Fun stuff is cool to write, but painful to read. It's even more painful to edit and maintain. As developers, we must show the community that they should use cleaner code, instead of faster, wobbling code. The exception is made when there is a significant performance issue and the wobbling thing is greatly resolving the issue.
– Frederik.L
May 31 '16 at 6:09
1
@Frederik.L I totally agree about writing cleaner code. Then I totally accept the downvotes. Thank you.
– ceremcem
May 31 '16 at 14:34
Because it's fun :) But stackoverflow is such a strange place that you may get a down vote or may be questioned even though your code works as intended and might help the OP or someone else in some way...
– ceremcem
May 29 '16 at 4:47
Because it's fun :) But stackoverflow is such a strange place that you may get a down vote or may be questioned even though your code works as intended and might help the OP or someone else in some way...
– ceremcem
May 29 '16 at 4:47
1
1
@MrMesees—what existing Date function functionality is that?
– RobG
May 29 '16 at 8:54
@MrMesees—what existing Date function functionality is that?
– RobG
May 29 '16 at 8:54
@RobG I was not aware of problems in
Date.parse
at the time of the comment, it's been removed. I still think that this is not very friendly code example.– MrMesees
May 30 '16 at 4:51
@RobG I was not aware of problems in
Date.parse
at the time of the comment, it's been removed. I still think that this is not very friendly code example.– MrMesees
May 30 '16 at 4:51
@ceremcem I did not down vote your answer since other people did enough yet, but I can explain why it got down votes and why I usually down vote answers like this on SO. Fun stuff is cool to write, but painful to read. It's even more painful to edit and maintain. As developers, we must show the community that they should use cleaner code, instead of faster, wobbling code. The exception is made when there is a significant performance issue and the wobbling thing is greatly resolving the issue.
– Frederik.L
May 31 '16 at 6:09
@ceremcem I did not down vote your answer since other people did enough yet, but I can explain why it got down votes and why I usually down vote answers like this on SO. Fun stuff is cool to write, but painful to read. It's even more painful to edit and maintain. As developers, we must show the community that they should use cleaner code, instead of faster, wobbling code. The exception is made when there is a significant performance issue and the wobbling thing is greatly resolving the issue.
– Frederik.L
May 31 '16 at 6:09
1
1
@Frederik.L I totally agree about writing cleaner code. Then I totally accept the downvotes. Thank you.
– ceremcem
May 31 '16 at 14:34
@Frederik.L I totally agree about writing cleaner code. Then I totally accept the downvotes. Thank you.
– ceremcem
May 31 '16 at 14:34
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37505117%2ffind-the-next-closest-date-in-mm-dd-yyy-format-javascript%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Do you only need the very closest date or many of them? Since many solutions uses sorting algorithms and assuming this.
– Frederik.L
May 29 '16 at 2:00
1
All the answers here suggest parsing the strings with the Date constructor. Don't do that. Manually parse strings (a library can help but isn't necessary).
– RobG
May 29 '16 at 9:02
@RobG my answer does not suggest parsing strings with date constructor; it suggests altering the format, and using built-in Date.parse
– MrMesees
May 29 '16 at 12:40
1
@MrMesees—ok, then most of the answers. ;-)
– RobG
May 29 '16 at 22:59