C#30 Days from Todays Date

时间:2009-11-03 08:24:41

标签: c# datetime

我需要我的应用程序从今天起30天过期,我会将当前日期存储在应用程序配置中。如何检查应用程序是否已过期?我不介意用户是否更改了时钟并且应用程序正常工作(用户太愚蠢了)。

if (appmode == "Trial") {               

            ????

            }

12 个答案:

答案 0 :(得分:50)

string dateInString = "01.10.2009";

DateTime startDate = DateTime.Parse(dateInString);
DateTime expiryDate = startDate.AddDays(30);
if (DateTime.Now > expiryDate) {
  //... trial expired
}

答案 1 :(得分:20)

DateTime.AddDays这样做:

DateTime expires = yourDate.AddDays(30);

答案 2 :(得分:13)

我可以自信地回答!

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

或者可能 - 如果您只是希望没有附加时间的日期可能更合适:

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

答案 3 :(得分:13)

DateTime.Now.Add(-30)

给你30天后的日期

答案 4 :(得分:4)

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

答案 5 :(得分:2)

可能的解决方案是首次运行,创建一个包含当前日期的文件并将其放入IsolatedStorage。对于后续运行,检查文件的内容并与当前日期进行比较;如果日期差异大于30天,请通知用户并关闭应用程序。

答案 6 :(得分:1)

更好的解决方案可能是引入带计数器的许可证文件。将许可证文件写入应用程序的安装日期(安装期间)。然后,每次运行应用程序时,您都可以编辑许可证文件并将计数增加1.每次应用程序启动时,您只需快速检查是否已达到应用程序的30次使用,即

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

如果用户已将系统时钟恢复原状,这也可以解决问题,因为您可以进行简单的检查来说明

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

您当前设置的问题是用户必须每天使用该应用程序30天才能完成30天的试用。

答案 7 :(得分:1)

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;
        }
    }

我在某些网站的某些部分看到了该代码。上面的示例暴露了一个小故障:将当前时间和日期更改为开始日期会延长应用程序到期时间。

解决方案?请参阅在线时间服务器。

答案 8 :(得分:0)

@Ed courtenay,@ James, 我有一个愚蠢的问题。 如何让用户远离此文件?(包含失效日期的文件)。 如果用户具有安装权限,那么显然用户也可以访问查看文件。 更改文件的扩展名不会有帮助。 那么,如何保护这个文件安全并远离用户手?

答案 9 :(得分:0)

您需要存储程序的第一次运行时才能执行此操作。我怎么可能这样做是使用visual studio中的内置应用程序设置。制作一个名为InstallDate的用户设置,默认为DateTime.MinValue或类似的东西(例如1/1/1900)。

然后当程序运行时,检查很简单:

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.)
  }
}

用户设置存储在一个非常奇怪的位置(类似于C:\ Documents and Settings \ YourName \ Local Settings \ Application Data),因此无论如何平均乔很难找到它。如果你想成为偏执狂,只需加密日期,然后再将其保存到设置中。

编辑:叹息,误读了这个问题,没有像我想象的那么复杂&gt;。&gt;

答案 10 :(得分:0)

这个问题有点晚了,但是我创建了一个类,其中包含在C#中创建功能齐全的计时功能所需的所有便捷方法。我将到期时间写入Windows应用程序数据路径,而不是您的应用程序配置,即使在程序关闭后,该时间也将保持不变(找到普通用户的路径也很棘手)。

完整记录且易于使用,希望有人觉得它有用!

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); }
    }

}

这是以上类的典型用法。再简单不过了!

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); }
}

答案 11 :(得分:-2)

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;

                        }

                    }
                }