C# 从今天起 30 天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1665941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:49:33  来源:igfitidea点击:

C# 30 Days From Todays Date

c#datetime

提问by abmv

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

我需要我的应用程序从今天起 30 天到期,我会将当前日期存储在应用程序配置中。我将如何检查应用程序是否已过期?我不介意用户是否更改了时钟并且应用程序可以运行(用户太愚蠢了,无法这样做)。

if (appmode == "Trial") {               

            ????

            }

采纳答案by Fredrik M?rk

string dateInString = "01.10.2009";

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

回答by SWeko

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

回答by Murph

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

回答by Fredrik M?rk

DateTime.AddDaysdoes that:

DateTime.AddDays这样做:

DateTime expires = yourDate.AddDays(30);

回答by James

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.

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

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.

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

回答by Ed Courtenay

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.

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

回答by Shekhar

@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?

@Ed Courtenay,@James,我有一个愚蠢的问题。如何让用户远离这个文件?(包含到期日期的文件)。如果用户具有安装权限,那么显然用户也有权查看文件。更改文件的扩展名无济于事。那么,如何保证这个文件的安全并远离用户的手呢?

回答by mike

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

您需要存储程序的第一次运行时间才能执行此操作。我可能会如何使用 Visual Studio 中的内置应用程序设置。制作一个名为 InstallDate 的用户设置,默认为 DateTime.MinValue 或类似的东西(例如 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.

用户设置存储在一个非常奇怪的位置(例如 C:\Documents and Settings\YourName\Local Settings\Application Data),因此普通人无论如何都很难找到它。如果您想变得偏执,只需在将日期保存到设置之前加密日期即可。

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

编辑:唉,误读了这个问题,没有我想象的那么复杂>.>

回答by Zyon

DateTime.Now.Add(-30)

日期时间.现在.添加(-30)

Gives you the date 30 days back from now

为您提供 30 天后的日期

回答by SkyRune

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.

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