1 // Copyright 2020 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/metrics/date_changed_helper.h"
7 #include "base/time/time.h"
8 #include "components/prefs/pref_registry_simple.h"
9 #include "components/prefs/pref_service.h"
15 base::Time GetCurrentDate(base::Time now) {
16 // Use local midnight to ensure reporting is for calendar days, not UTC, and
17 // avoid storing extra information about when this was called.
18 return now.LocalMidnight();
21 void UpdateStoredDate(PrefService* prefs,
22 const char* pref_name,
24 prefs->SetTime(pref_name, GetCurrentDate(now));
27 bool IsStoredDateToday(PrefService* prefs,
28 const char* pref_name,
30 base::Time stored_date = prefs->GetTime(pref_name);
31 if (stored_date.is_null()) {
32 // Consider date unchanged if pref has never been set.
33 UpdateStoredDate(prefs, pref_name, GetCurrentDate(now));
36 // Ignore small changes in midnight such as time zone changes.
37 return std::abs((stored_date - GetCurrentDate(now)).InHours()) < 12;
42 namespace date_changed_helper {
44 bool HasDateChangedSinceLastCall(PrefService* prefs, const char* pref_name) {
47 base::Time now = base::Time::Now();
48 if (IsStoredDateToday(prefs, pref_name, now))
50 UpdateStoredDate(prefs, pref_name, now);
54 void RegisterPref(PrefRegistrySimple* registry, const char* pref_name) {
55 registry->RegisterTimePref(pref_name, base::Time());
58 } // namespace date_changed_helper
60 } // namespace metrics