Random Date in C#

Random date in C#

private Random gen = new Random();
DateTime RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
int range = (DateTime.Today - start).Days;
return start.AddDays(gen.Next(range));
}

For better performance if this will be called repeatedly, create the start and gen (and maybe even range) variables outside of the function.

Generate random date and time in a service

It seems to me like the main problem here is simply to create a method that generates a random date.

One way to do this and retain a certain level of control over which dates you get, is to just generate random numbers for date, month and year. For year, you could do:

Random r = new Random();

int randomYear = r.Next(1990, 2015); // random year between 1990 and 2014
int randomMonthNr = r.Next(1,13);
int maxDayNr = DateTime.DaysInMonth(randomYear, randomMonthNr);
int randomDayNr = r.Next(1, (maxDayNr + 1));

Do something similar for date and month, and just use that in:

var randomDate = new DateTime(randomYear, randomMonthNr, randomDayNr);

(Note: Generate the month first, then find out the number of days in the resulting month, and use that as the upper limit when generating a number for the date, so you get a max of 28 or 29 for February, etc).

Once the date(s) are created, you can simply compare them using <= and >= (with or without the =). If you need to compare them within the context of the service, just send a DateTime as a parameter to the service, and compare it there.


Update: Connecting to the service

Open the folder under your Visual Studio project for the client. Right click the service reference, and select View in Object Browser. There, you should see a hierarchy of the types and namespaces from your service. Look for a type called something like YourServiceNameClient. This will be an automatically generated type that you can use to connect to your service (Client will just be appended to the type that the service reference has identified).

Use it like:

var yourServiceReference = new YourServiceNameClient();
var yourGeneratedDate = yourServiceReference.GetNewRandomDate();

This obviously assumes GetNewRandomDate() is a method you have exposed in your service. Hope this is helpful...

How to get both Random Date and Time C#

Here's a method that'll randomly generate every portion of the date and time.

It uses appropriate limits so the generated date is valid (years within 1-9999, months within 1-12, a call to DateTime.DaysInMonth so we don't end up with Feb 31, etc).

public IEnumerable<DateTime> GenerateRandomDates(int numberOfDates)
{
var rnd = new Random(Guid.NewGuid().GetHashCode());

for (int i = 0; i < numberOfDates; i++)
{
var year = rnd.Next(1, 10000);
var month = rnd.Next(1, 13);
var days = rnd.Next(1, DateTime.DaysInMonth(year, month) + 1);

yield return new DateTime(year, month, days,
rnd.Next(0, 24), rnd.Next(0, 60), rnd.Next(0, 60), rnd.Next(0, 1000));
}
}

To generate 10,000 of them:

var randomDateTimes = GenerateRandomDates(10000);

How can I generate random dates within a range?

void Main()
{
Console.WriteLine(DateTime.UtcNow.AddDays(new Random().Next(90)));
}

This will add a random amount of days to the start date, essentially ending up with a random date.

Random DateTime between range - not unified output

You could change to:

static readonly Random rnd = new Random();
public static DateTime GetRandomDate(DateTime from, DateTime to)
{
var range = to - from;

var randTimeSpan = new TimeSpan((long)(rnd.NextDouble() * range.Ticks));

return from + randTimeSpan;
}

Explanation: I used NextDouble() because it gives a number between 0.0 and 1.0. Your return value won't be a whole number of seconds in my solution. And I moved rnd out to a field on the class/struct. Because it's best to reuse one Random instance, and not create a new one every time one needs just one additional random number.

What's the best practice for getting a random DateTime between two date-times?

You could try using:

var randomTest = new Random();

TimeSpan timeSpan = endDate - startDate;
TimeSpan newSpan = new TimeSpan(0, randomTest.Next(0, (int)timeSpan.TotalMinutes), 0);
DateTime newDate = startDate + newSpan;

This will give you different times down to the minute. If you want 100 (or any thing more than 1) DateTimes then only create the Random object once. The MSDN page on Random explains in detail why creating several Random objects in quick succession is a bad idea.

Using a different TimeSpan constructor will give you different granularity. From the TimeSpan constructor MSDN:

TimeSpan(Int64) Initializes a new TimeSpan to the specified number of ticks.

TimeSpan(Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of hours, minutes, and seconds.

TimeSpan(Int32, Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of
days, hours, minutes, and seconds.

TimeSpan(Int32, Int32, Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of days, hours, minutes, seconds, and milliseconds.

Random date format read from Excel

To convert date number or date string to c# you need two different methods.

One to convert string and the other one to convert number to date format.

So, regarding converting string to date, there are TryParse method in c#, and regarding the number conversation to date there are already answer on that in SO.

Putting that together we can do some thing like:

public static DateTime? GetDateTime(object o)
{
DateTime? date;
try
{
date = FromStringToDate(o.ToString());
if (date == DateTime.MinValue)
{
date = FromExcelSerialDate((int)o);
}
}
catch (Exception e)
{
//log your exception
date = null;
}

return date;
}

private static DateTime FromExcelSerialDate(int serialDate)
{
if (serialDate > 59) serialDate -= 1; //Excel/Lotus 2/29/1900 bug
return new DateTime(1899, 12, 31).AddDays(serialDate);
}

private static DateTime FromStringToDate(string stringDate)
{
DateTime.TryParse(stringDate, out DateTime result);
return result;
}

To put that in use, in your main method for testing you can do some thing like:

List<object> excelData = new List<object>()
{
"16.02.1995",
41187,
13131.3242,
"",
null
};

foreach (object o in excelData)
{
var dateTime = GetDateTime(o);
if (dateTime != null)
{
Console.WriteLine(dateTime);
}
}

The output will be:

16-02-1995 00:00:00    
05-10-2012 00:00:00

I have testing it i excel as well.

Sample Image

Note: This is just example, you might improve the methods, change the order, adding more protective lines so it does not break, for example if date is null, empty or wrong format in excel to fit you business logic.



Related Topics



Leave a reply



Submit