C# 从今天开始的30天

30

我希望我的应用程序从今天起30天后过期,我将当前日期存储在应用程序配置中。如何检查应用程序是否已过期?如果用户将时钟往回更改并且应用程序仍能运行(用户太愚蠢了),那么我不介意。

if (appmode == "Trial") {               

            ????

            }
13个回答

64
string dateInString = "01.10.2009";

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

DateTime expiryDate = new DateTime(startDate); 不是必需的。 - Scoregraphic
6
DateTime expiryDate = startDate.AddDays(30); 是正确的,因为 expiryDate.AddDays(30) 会把结果写入虚无之中。 - Oliver

23

DateTime.AddDays可以实现这一功能:

DateTime expires = yourDate.AddDays(30);

2
请记得赋值返回结果。我总是运行"yourdate.AddDays(30)",然后想知道为什么“yourDate”没有改变。 - Cameron MacFarland
1
你的日期并没有改变,实际上是过期日期在改变,所以在这种情况下没问题。 - James
@Cameron:这就是 DateTime expires 部分发挥作用的地方。 - Fredrik Mörk
你可以使用 Date.Now.Date.ToString 来获取当前日期的经典格式。 - Emanuel Pirovano
寻找它已经很久了。 - γηράσκω δ' αεί πολλά διδασκόμε

20

DateTime.Now.Add(-30)

这段代码会返回当前时间向前推 30 天的日期。


它应该是 DateTime.Now.AddDays(-30) - Nagaraj Raveendran

15

有一个问题我可以自信地回答!

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

或者,如果您只想要日期而没有时间的话,这可能更为合适:

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

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

2

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


1
+1 独立存储正在发挥作用...注册表也可能是另一个选择,尽管需要比独立存储更多的安全性。 - Ian

1

你只需要使用DateTime.AddDays

例如:

从今天开始加30天:

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

从今天开始减去30天:

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

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天试用期。

从安装日期或首次使用日期起30天并不罕见或不合理。 - Murph
1
是的,但正如我所提到的,您必须在连续30天内每天使用该应用程序才能获得完整的30天试用期。现在大多数应用程序都会确保您无论何时第一次使用/安装应用程序都能获得完整的30天。 - James

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

我在某个网站的某个部分看到了那段代码。上面的示例揭示了一个漏洞:将当前时间和日期更改为开始日期会延长应用程序的过期时间。

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


七月和八月都有31天。但在你的代码中,(7%2 = 1)E(8%2 = 0)。 - Henrique

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),因此对于普通用户来说,找到它将会非常困难。如果您想要更加谨慎,只需在保存设置之前对数据进行加密。

编辑:唉,我误读了问题,它并不像我想象的那么复杂 >.>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接