Skip to content

Commit

Permalink
Merge pull request #138 from unindented/master
Browse files Browse the repository at this point in the history
[fix] Have past, future and recent return random dates #110
  • Loading branch information
Marak committed Nov 19, 2014
2 parents 3960181 + ba482f1 commit fd5d874
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
20 changes: 17 additions & 3 deletions lib/date.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,27 @@ var date = {

past: function (years, refDate) {
var date = (refDate) ? new Date(Date.parse(refDate)) : new Date();
var range = {
min: 1000,
max: (years || 1) * 365 * 24 * 3600 * 1000
};

var past = date.getTime();
past -= faker.random.number(years) * 365 * 24 * 3600 * 1000; // some time from now to N years ago, in milliseconds
past -= faker.random.number(range); // some time from now to N years ago, in milliseconds
date.setTime(past);

return date;
},

future: function (years, refDate) {
var date = (refDate) ? new Date(Date.parse(refDate)) : new Date();
var range = {
min: 1000,
max: (years || 1) * 365 * 24 * 3600 * 1000
};

var future = date.getTime();
future += faker.random.number(years) * 365 * 3600 * 1000 + 1000; // some time from now to N years later, in milliseconds
future += faker.random.number(range); // some time from now to N years later, in milliseconds
date.setTime(future);

return date;
Expand All @@ -32,8 +41,13 @@ var date = {

recent: function (days) {
var date = new Date();
var range = {
min: 1000,
max: (days || 1) * 24 * 3600 * 1000
};

var future = date.getTime();
future -= faker.random.number(days) * 24 * 60 * 60 * 1000; // some time from now to N days ago, in milliseconds
future -= faker.random.number(range); // some time from now to N days ago, in milliseconds
date.setTime(future);

return date;
Expand Down
10 changes: 9 additions & 1 deletion test/date.unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ describe("date.js", function () {
assert.ok(date < new Date());
});

it("returns a past date when N = 0", function () {

var refDate = new Date();
var date = faker.date.past(0, refDate.toJSON());

assert.ok(date < refDate); // date should be before the date given
});

it("returns a date N years before the date given", function () {

var refDate = new Date(2120, 11, 9, 10, 0, 0, 0); // set the date beyond the usual calculation (to make sure this is working correctly)
Expand All @@ -36,7 +44,7 @@ describe("date.js", function () {
var refDate = new Date();
var date = faker.date.future(0, refDate.toJSON());

assert.ok(date > refDate); // date should be after the date given, but before the current time
assert.ok(date > refDate); // date should be after the date given
});

it("returns a date N years after the date given", function () {
Expand Down

0 comments on commit fd5d874

Please sign in to comment.