Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add dateTimeBetween method to date.dart #55

Merged
merged 2 commits into from
Apr 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions example/faker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ void main() {
// Generate random DateTime, between the years 2000 and 2020
print(faker.date.dateTime(minYear: 2000, maxYear: 2020));

// Generate random DateTime, between the 2 dates
print(faker.date.dateTimeBetween(DateTime(2017, 9, 7), DateTime(2020, 9, 7)));

// Generate random User Agent, with osName iOS
print(faker.internet.userAgent(osName: 'iOS'));

Expand Down
20 changes: 20 additions & 0 deletions lib/src/date.dart
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,26 @@ class Date {
);
}

/// Generates a random [DateTime] in between 2 given dates.
/// This is accurate to the nearest hour.
/// Example:
/// ```dart
/// faker.date.dateTimeBetween(DateTime(2017, 9, 7), DateTime(2020, 9, 7));
/// ```
DateTime dateTimeBetween(DateTime startDate, DateTime endDate) {
final hoursInBetween = endDate.difference(startDate).inHours;
return DateTime(
startDate.year, // year
startDate.month, // month
startDate.day, // day
startDate.hour + random.integer(hoursInBetween), // hour
random.integer(60), // minute
random.integer(60), // second
random.integer(1000), // millisecond
random.integer(1000), // microsecond
);
}

/// Generates a random month
///
/// Example:
Expand Down
8 changes: 8 additions & 0 deletions test/specs/date.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ void main() {
expect(true, faker.date.dateTime() is DateTime);
});

test('should be able to generate a DateTime between 2 DateTimes', () {
final fromDate = DateTime(1920);
final toDate = DateTime.now();
final fakeDateTime = faker.date.dateTimeBetween(fromDate, toDate);
expect(true,
fakeDateTime.isAfter(fromDate) && fakeDateTime.isBefore(toDate));
});

test('should be able to generate a month', () {
expect(faker.date.month(), matches(RegExp(r'^([\w\s\-])+$')));
});
Expand Down