diff --git a/README.md b/README.md index 5fd32059..b42992d1 100644 --- a/README.md +++ b/README.md @@ -627,6 +627,7 @@ Svg(options *SVGOptions) string ```go Date() time.Time +PastDate() time.Time FutureDate() time.Time DateRange(start, end time.Time) time.Time NanoSecond() int diff --git a/time.go b/time.go index 3d580d3a..10f7e9e8 100644 --- a/time.go +++ b/time.go @@ -17,6 +17,16 @@ func date(r *rand.Rand) time.Time { return time.Date(year(r), time.Month(month(r)), day(r), hour(r), minute(r), second(r), nanoSecond(r), time.UTC) } +// FutureDate will generate a random past time.Time struct +func PastDate() time.Time { return pastDate(globalFaker.Rand) } + +// FutureDate will generate a random past time.Time struct +func (f *Faker) PastDate() time.Time { return pastDate(f.Rand) } + +func pastDate(r *rand.Rand) time.Time { + return time.Now().Add(time.Hour * -time.Duration(number(r, 1, 12))) +} + // FutureDate will generate a random future time.Time struct func FutureDate() time.Time { return futureDate(globalFaker.Rand) } @@ -311,6 +321,28 @@ func addDateTimeLookup() { }, }) + AddFuncLookup("pasttime", Info{ + Display: "PastTime", + Category: "time", + Description: "Random past date", + Example: "2007-01-24 13:00:35.820738079 +0000 UTC", + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return pastDate(r), nil + }, + }) + + AddFuncLookup("futuretime", Info{ + Display: "FutureTime", + Category: "time", + Description: "Random past date", + Example: "2107-01-24 13:00:35.820738079 +0000 UTC", + Output: "string", + Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + return futureDate(r), nil + }, + }) + AddFuncLookup("nanosecond", Info{ Display: "Nanosecond", Category: "time", diff --git a/time_test.go b/time_test.go index acd372ef..da5bc38a 100644 --- a/time_test.go +++ b/time_test.go @@ -56,6 +56,48 @@ func BenchmarkDate(b *testing.B) { }) } +func ExamplePastDate() { + Seed(11) + fmt.Println(PastDate()) +} + +func ExampleFaker_PastDate() { + f := New(11) + fmt.Println(f.PastDate()) +} + +func TestPastDate(t *testing.T) { + now := time.Now() + pastDate := PastDate() + if now.Before(pastDate) { + t.Error("Expected time from past, got: ", pastDate) + } +} + +func BenchmarkPastDate(b *testing.B) { + b.Run("package", func(b *testing.B) { + for i := 0; i < b.N; i++ { + PastDate() + } + }) + + b.Run("Faker math", func(b *testing.B) { + f := New(0) + + for i := 0; i < b.N; i++ { + f.PastDate() + } + }) + + b.Run("Faker crypto", func(b *testing.B) { + f := NewCrypto() + + for i := 0; i < b.N; i++ { + f.PastDate() + } + }) +} + func ExampleFutureDate() { Seed(11) fmt.Println(FutureDate())