[c#] C# 30 Days From Todays Date

I need my application to expire 30 days from today, I will store the current date in the application config.How will I check if the application has expired ? I don't mind if the user changed the clock back and the app works (too stupid a user to do that).

if (appmode == "Trial") {               

            ????

            }

This question is related to c# datetime

The answer is


if (cmb_mode_of_service.SelectedItem != null && cmb_term_of_service.SelectedItem != null)
            {
                if (cmb_mode_of_service.SelectedIndex > 0 && cmb_term_of_service.SelectedIndex > 0)
                {
                    if (cmb_mode_of_service.SelectedItem.ToString() == "Single Service/Installation" || cmb_term_of_service.SelectedItem.ToString() == "Single Time")
                    {
                        int c2 = 1;
                        char c1 = 'A';
                        DataRow dr = dt.NewRow();
                        dr["SN"] = c2++;
                        dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                        dr["servicedate"] = service_start_date.Text;
                        dr["servicestatus"] = "Pending";
                        dr["serviceexcutive"] = "Not Alowed";
                        dt.Rows.Add(dr);
                        dataGridView1.DataSource = dt;

                        txtexpirydate.Text = (Convert.ToDateTime(service_start_date.Text).AddDays(1)).ToString();

                    }
                    else
                    {



                        if (cmb_mode_of_service.SelectedItem.ToString() == "Weekly Service")
                        {
                            int year = 0;
                            if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                            {
                                year = 1;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                            {
                                year = 2;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                            {
                                year = 3;
                            }

                            DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                            DateTime Enddate = currentdate.AddYears(+year);
                            txtexpirydate.Text = Enddate.ToString();

                            char c1 = 'A';
                            int c2 = 1;
                            for (var dt1 = currentdate.AddDays(7); dt1 <= Enddate; dt1 = dt1.AddDays(7))
                            {
                                DataRow dr = dt.NewRow();
                                dr["SN"] = c2++;
                                dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                                dr["servicedate"] = dt1.ToString();
                                dr["servicestatus"] = "Pending";
                                dr["serviceexcutive"] = "Not Alowed";
                                //txtexpirydate.Text = dt1.ToString();
                                dt.Rows.Add(dr);

                            }
                            dataGridView1.DataSource = dt;

                        }

                        if (cmb_mode_of_service.SelectedItem.ToString() == "Fortnight Service")
                        {
                            int year = 0;
                            if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                            {
                                year = 1;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                            {
                                year = 2;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                            {
                                year = 3;
                            }

                            DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                            DateTime Enddate = currentdate.AddYears(+year);
                            txtexpirydate.Text = Enddate.ToString();

                            char c1 = 'A';
                            int c2 = 1;
                            for (var dt1 = currentdate.AddDays(15); dt1 <= Enddate; dt1 = dt1.AddDays(15))
                            {
                                DataRow dr = dt.NewRow();
                                dr["SN"] = c2++;
                                dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                                dr["servicedate"] = dt1.ToString();
                                dr["servicestatus"] = "Pending";
                                dr["serviceexcutive"] = "Not Alowed";
                                //  txtexpirydate.Text = dt1.ToString();
                                dt.Rows.Add(dr);

                            }
                            dataGridView1.DataSource = dt;

                        }

                        if (cmb_mode_of_service.SelectedItem.ToString() == "Monthly Service")
                        {
                            int year = 0;
                            if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                            {
                                year = 1;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                            {
                                year = 2;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                            {
                                year = 3;
                            }

                            DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                            DateTime Enddate = currentdate.AddYears(+year);
                            txtexpirydate.Text = Enddate.ToString();

                            char c1 = 'A';
                            int c2 = 1;
                            for (var dt1 = currentdate.AddDays(30); dt1 <= Enddate; dt1 = dt1.AddDays(30))
                            {
                                DataRow dr = dt.NewRow();
                                dr["SN"] = c2++;
                                dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                                dr["servicedate"] = dt1.ToString();
                                dr["servicestatus"] = "Pending";
                                dr["serviceexcutive"] = "Not Alowed";
                                // txtexpirydate.Text = dt1.ToString();
                                dt.Rows.Add(dr);

                            }
                            dataGridView1.DataSource = dt;

                        }


                        if (cmb_mode_of_service.SelectedItem.ToString() == "Trimister Service")
                        {
                            int year = 0;
                            if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                            {
                                year = 1;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                            {
                                year = 2;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                            {
                                year = 3;
                            }

                            DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                            DateTime Enddate = currentdate.AddYears(+year);
                            txtexpirydate.Text = Enddate.ToString();

                            char c1 = 'A';
                            int c2 = 1;
                            for (var dt1 = currentdate.AddDays(90); dt1 <= Enddate; dt1 = dt1.AddDays(90))
                            {
                                DataRow dr = dt.NewRow();
                                dr["SN"] = c2++;
                                dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                                dr["servicedate"] = dt1.ToString();
                                dr["servicestatus"] = "Pending";
                                dr["serviceexcutive"] = "Not Alowed";
                                // txtexpirydate.Text = dt1.ToString();
                                dt.Rows.Add(dr);

                            }
                            dataGridView1.DataSource = dt;

                        }

                        if (cmb_mode_of_service.SelectedItem.ToString() == "Half Yearly Service")
                        {
                            int year = 0;
                            if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                            {
                                year = 1;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                            {
                                year = 2;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                            {
                                year = 3;
                            }

                            DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                            DateTime Enddate = currentdate.AddYears(+year);
                            txtexpirydate.Text = Enddate.ToString();

                            char c1 = 'A';
                            int c2 = 1;
                            for (var dt1 = currentdate.AddDays(180); dt1 <= Enddate; dt1 = dt1.AddDays(180))
                            {
                                DataRow dr = dt.NewRow();
                                dr["SN"] = c2++;
                                dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                                dr["servicedate"] = dt1.ToString();
                                dr["servicestatus"] = "Pending";
                                dr["serviceexcutive"] = "Not Alowed";
                                //  txtexpirydate.Text = dt1.ToString();
                                dt.Rows.Add(dr);

                            }
                            dataGridView1.DataSource = dt;

                        }

                        if (cmb_mode_of_service.SelectedItem.ToString() == "Yearly Service")
                        {
                            int year = 0;
                            if (cmb_term_of_service.SelectedItem.ToString() == "One Year")
                            {
                                year = 1;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "Two Year")
                            {
                                year = 2;
                            }

                            if (cmb_term_of_service.SelectedItem.ToString() == "three year")
                            {
                                year = 3;
                            }

                            DateTime currentdate = Convert.ToDateTime(service_start_date.Text);
                            DateTime Enddate = currentdate.AddYears(+year);
                            txtexpirydate.Text = Enddate.ToString();

                            char c1 = 'A';
                            int c2 = 1;
                            for (var dt1 = currentdate.AddDays(365); dt1 <= Enddate; dt1 = dt1.AddDays(365))
                            {
                                DataRow dr = dt.NewRow();
                                dr["SN"] = c2++;
                                dr["serviceid"] = txt_service_id.Text + "-" + c1++;
                                dr["servicedate"] = dt1.ToString();
                                dr["servicestatus"] = "Pending";
                                dr["serviceexcutive"] = "Not Alowed";
                                //txtexpirydate.Text = dt1.ToString();
                                dt.Rows.Add(dr);

                            }
                            dataGridView1.DataSource = dt;

                        }

                    }
                }

@Ed courtenay, @James, I have one stupid question. How to keep user away from this file?(File containing expiry date). If the user has installation rights, then obviously user has access to view files also. Changing the extension of file wont help. So, how to keep this file safe and away from users hands?


string[] servers = new string[] {
        "nist1-ny.ustiming.org",
        "nist1-nj.ustiming.org",
        "nist1-pa.ustiming.org",
        "time-a.nist.gov",
        "time-b.nist.gov",
        "nist1.aol-va.symmetricom.com",
        "nist1.columbiacountyga.gov",
        "nist1-chi.ustiming.org",
        "nist.expertsmi.com",
        "nist.netservicesgroup.com"
        };
string dateStart, dateEnd;

void SetDateToday()
    {
        Random rnd = new Random();
        DateTime result = new DateTime();
        int found = 0;
        foreach (string server in servers.OrderBy(s => rnd.NextDouble()).Take(5))
        {
            Console.Write(".");
            try
            {
                string serverResponse = string.Empty;
                using (var reader = new StreamReader(new System.Net.Sockets.TcpClient(server, 13).GetStream()))
                {
                    serverResponse = reader.ReadToEnd();
                    Console.WriteLine(serverResponse);
                }

                if (!string.IsNullOrEmpty(serverResponse))
                {
                    string[] tokens = serverResponse.Split(' ');
                    string[] date = tokens[1].Split(' ');
                    string time = tokens[2];
                    string properTime;

                    dateStart = date[2] + "/" + date[0] + "/" + date[1];

                    int month = Convert.ToInt16(date[0]), day = Convert.ToInt16(date[2]), year = Convert.ToInt16(date[1]);
                    day = day + 30;
                    if ((month % 2) == 0)
                    {
                        //MAX DAYS IS 30
                        if (day > 30)
                        {
                            day = day - 30;
                            month++;
                            if (month > 12)
                            {
                                month = 1;
                                year++;
                            }
                        }
                    }
                    else
                    {
                        //MAX DAYS IS 31
                        if (day > 31)
                        {
                            day = day - 31;
                            month++;
                            if (month > 12)
                            {
                                month = 1;
                                year++;
                            }
                        }
                    }
                    string sday, smonth;
                    if (day < 10)
                    {
                        sday = "0" + day;
                    }
                    if (month < 10)
                    {
                        smonth = "0" + month;
                    }
                    dateEnd = sday + "/" + smonth + "/" + year.ToString();

                }

            }
            catch
            {
                // Ignore exception and try the next server
            }
        }
        if (found == 0)
        {
            MessageBox.Show(this, "Internet Connection is required to complete Registration. Please check your internet connection and try again.", "Not connected", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Success = false;
        }
    }

I saw that code in some part of some website. Doing the example above exposes a glitch: Changing the current Time and Date to the start date would prolong the application expiration.

The solution? Refer to a online time server.


One I can answer confidently!

DateTime expiryDate = DateTime.Now.AddDays(30);

Or possibly - if you just want the date without a time attached which might be more appropriate:

DateTime expiryDate = DateTime.Today.AddDays(30);

DateTime.AddDays does that:

DateTime expires = yourDate.AddDays(30);

DateTime.Now.Add(-30)

Gives you the date 30 days back from now


DateTime _expiryDate = DateTime.Now + TimeSpan.FromDays(30);

You need to store the first run time of the program in order to do this. How I'd probably do it is using the built in application settings in visual studio. Make one called InstallDate which is a User Setting and defaults to DateTime.MinValue or something like that (e.g. 1/1/1900).

Then when the program is run the check is simple:

if (appmode == "trial")
{
  // If the FirstRunDate is MinValue, it's the first run, so set this value up
  if (Properties.Settings.Default.FirstRunDate == DateTime.MinValue)
  {
    Properties.Settings.Default.FirstRunDate = DateTime.Now;
    Properties.Settings.Default.Save(); 
  }

  // Now check whether 30 days have passed since the first run date
  if (Properties.Settings.Default.FirstRunDate.AddMonths(1) < DateTime.Now)
  {
    // Do whatever you want to do on expiry (exception message/shut down/etc.)
  }
}

User settings are stored in a pretty weird location (something like C:\Documents and Settings\YourName\Local Settings\Application Data) so it will be pretty hard for average joe to find it anyway. If you want to be paranoid, just encrypt the date before saving it to settings.

EDIT: Sigh, misread the question, not as complex as I thought >.>


A bit late to this question, but I created a class with all the handy methods needed to create a fully functional time trial in C#. Rather than your application config, I write the expiry time to the Windows Application Data path, and that will also remain persistent even after the program has closed (it's also tricky to find the path for the average user).

Fully documented and simple to use, I hope someone finds it useful!

public class TimeTrialManager
{
    private long expiryTime=0;
    private string softwareName = "";
    private string userPath="";
    private bool useSeconds = false;

    public TimeTrialManager(string softwareName) {
        this.softwareName = softwareName;
        // Create folder in Windows Application Data folder for persistence:
        userPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\" + softwareName + "_prefs\\";
        if (!Directory.Exists(userPath)) Directory.CreateDirectory(Path.GetDirectoryName(userPath));
        userPath += "expiryinfo.txt";
    }

    // Use this method to check if the expiry has already been created. If
    // it has, you don't need to call the setExpiryDate() method ever again.
    public bool expiryHasBeenStored(){
        return File.Exists(userPath);
    }

    // Use this to set expiry as the number of days from the current time.
    // This should be called just once in the program's lifetime for that user.
    public void setExpiryDate(double days)  {
        DateTime time = DateTime.Now.AddDays(days);
        expiryTime = time.ToFileTimeUtc();
        storeExpiry(expiryTime.ToString() );
        useSeconds = false;
    }

    // Like above, but set the number of seconds. This should be just used for testing
    // as no sensible time trial would allow the user seconds to test the trial out:
    public void setExpiryTime(double seconds)   {
        DateTime time = DateTime.Now.AddSeconds(seconds);
        expiryTime = time.ToFileTimeUtc();
        storeExpiry(expiryTime.ToString());
        useSeconds = true;
    }

    // Check for this in a background timer or whenever else you wish to check if the time has run out
    public bool trialHasExpired()   {
        if(!File.Exists(userPath)) return false;
        if (expiryTime == 0)    expiryTime = Convert.ToInt64(File.ReadAllText(userPath));
        if (DateTime.Now.ToFileTimeUtc() >= expiryTime) return true; else return false;
    }

    // This method is optional and isn't required to use the core functionality of the class
    // Perhaps use it to tell the user how long he has left to trial the software
    public string expiryAsHumanReadableString(bool remaining=false) {
        DateTime dt = new DateTime();
        dt = DateTime.FromFileTimeUtc(expiryTime);
        if (remaining == false) return dt.ToShortDateString() + " " + dt.ToLongTimeString();
        else {
            if (useSeconds) return dt.Subtract(DateTime.Now).TotalSeconds.ToString();
            else return (dt.Subtract(DateTime.Now).TotalDays ).ToString();
        }
    }

    // This method is private to the class, so no need to worry about it
    private void storeExpiry(string value)  {
        try { File.WriteAllText(userPath, value); }
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }

}

Here is a typical usage of the above class. Couldn't be simpler!

TimeTrialManager ttm;
private void Form1_Load(object sender, EventArgs e)
{
    ttm = new TimeTrialManager("TestTime");
    if (!ttm.expiryHasBeenStored()) ttm.setExpiryDate(30); // Expires in 30 days time
}

private void timer1_Tick(object sender, EventArgs e)
{
    if (ttm.trialHasExpired()) { MessageBox.Show("Trial over! :("); Environment.Exit(0); }
}

A possible solution would be on first run, create a file containing the current date and put it in IsolatedStorage. For subsequent runs, check the contents of the file and compare with the current date; if the date difference is greater than 30 days, inform the user and close the application.


A better solution might be to introduce a license file with a counter. Write into the license file the install date of the application (during installation). Then everytime the application is run you can edit the license file and increment the count by 1. Each time the application starts up you just do a quick check to see if the 30 uses of the application has been reached i.e.

if (LicenseFile.Counter == 30)
    // go into expired mode

Also this will solve the issue if the user has put the system clock back as you can do a simple check to say

if (LicenseFile.InstallationDate < SystemDate)
    // go into expired mode (as punishment for trying to trick the app!) 

The problem with your current setup is the user will have to use the application every day for 30 days to get their full 30 day trial.