Create a random DateTime in the past, maximum 100 days ago. - CSharp System

CSharp examples for System:Random

Description

Create a random DateTime in the past, maximum 100 days ago.

Demo Code


using System.Text;
using System.Security.Cryptography;
using System;//from   w ww.ja v a  2  s  . co  m

public class Main{
        /// <summary>
        /// Create a random DateTime in the past, maximum 100 days ago.
        /// </summary>
        /// <returns>random boolean</returns>
        public static DateTime GenerateRandomDateInThePast()
        {
            int daysAgo = int.Parse(GeneratRandomNumber(2));
            return DateTime.Now.Date.AddDays(-daysAgo);
        }
        /// <summary>
        /// Create a random number as a string with a maximum length.
        /// </summary>
        /// <param name="length">Length of number</param>
        /// <returns>Generated string</returns>
        public static string GeneratRandomNumber(int length)
        {
            if (length > 0)
            {
                var sb = new StringBuilder();

                var rnd = SeedRandom();
                for (int i = 0; i < length; i++)
                {
                    sb.Append(rnd.Next(0, 9).ToString());
                }

                return sb.ToString();
            }

            return string.Empty;
        }
        private static Random SeedRandom()
        {
            return new Random(Guid.NewGuid().GetHashCode());
        }
}

Related Tutorials