简体   繁体   中英

what is the best way to know if it is the first time that the application is open in the day?

I'm looking for an example code how to know if it is the first time that the application is open in the day? I tried saving the current date in a .ini file and an key named open defined with boolean value and then compare:

DateTime.Now.Substract(*old date from .ini file*).TotalMinutes >= 0 

and after this, set open key in .ini file as true. how to implement it? there an way more easy to do it?

I need know of it because in first time that the application was open I'II update a list in database.

any help is appreciated. Thanks in advance.

应用程序设置中的每个用户将是我选择的位置。

"Best" is a moving target. For one app, one method may be best, but another app may need something completely different.

That said, you need a few concepts to be covered:

  1. Some place to remember the "last opened" time.
  2. Some code to check the time, update it, and do the once-per-day work.

From your question, #2 is pretty straightforward, once you know what #1 should be. So, here are some potential options for #1.

  1. Database (in a table tied to something like a user id)
  2. Ini file (as you mentioned)
  3. An xml file (maybe even inside app.config)

See my comments in your question regarding whether you are tracking on a lone workstation/multi-user, etc -- that will dictate where you store your date time (in the database, in machine-level scope, in user-level scope, etc).

Now as for what you store, if you are a multi-user app (or even mobile, like on a phone or laptop), don't forget to consider timezones. For that matter, don't forget to consider daylight savings time. (those changes in time could cause you to think that a day has passed, when it has not, or vice-versa).

I would recommend that you always store the time in UTC, and always compare in UTC:


// save the start time:
var startTime = DateTime.UtcNow;
(save the start time)
...
// comparing the times:
// also, are you worried about doing the check once per 24 hours, or do you want to go by calendar date?
// you already have code that does a once per 24hr check, so I will show code that goes by calendar days
if(startTime.Date < DateTime.UtcNow.Date)
  // hasn't run today
else
 // has run today

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM