117 lines
3.3 KiB
C#
117 lines
3.3 KiB
C#
using System;
|
||
using System.IO;
|
||
using UnityEngine;
|
||
|
||
public static class PersistentDateChecker
|
||
{
|
||
// 记录上一次检查的日期
|
||
private static DateTime _lastCheckDate;
|
||
|
||
// 存储日期的文件路径(可根据需要修改)
|
||
private static readonly string _dateFilePath;
|
||
|
||
static PersistentDateChecker()
|
||
{
|
||
_dateFilePath = Path.Combine(Application.streamingAssetsPath, "DateCheck.txt");
|
||
// 程序启动时读取上次保存的日期
|
||
LoadLastCheckDate();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 从文件加载上次检查的日期
|
||
/// </summary>
|
||
private static void LoadLastCheckDate()
|
||
{
|
||
try
|
||
{
|
||
if (File.Exists(_dateFilePath))
|
||
{
|
||
string dateString = File.ReadAllText(_dateFilePath).Trim();
|
||
// 尝试解析日期(只保留年月日)
|
||
if (DateTime.TryParse(dateString, out DateTime parsedDate))
|
||
{
|
||
_lastCheckDate = parsedDate.Date;
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
UnityEngine.Debug.Log($"加载日期文件失败: {ex.Message}");
|
||
}
|
||
|
||
// 如果文件不存在或解析失败,初始化为本天日期
|
||
_lastCheckDate = DateTime.Now.Date;
|
||
// 保存初始化的日期
|
||
SaveLastCheckDate();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将当前检查日期保存到文件
|
||
/// </summary>
|
||
private static void SaveLastCheckDate()
|
||
{
|
||
try
|
||
{
|
||
// 只保存日期部分(格式:yyyy-MM-dd)
|
||
File.WriteAllText(_dateFilePath, _lastCheckDate.ToString("yyyy-MM-dd"));
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
UnityEngine.Debug.Log($"保存日期文件失败: {ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 判断当前是否为新的一天(相对于上一次记录的日期)
|
||
/// </summary>
|
||
/// <returns>如果是新的一天则返回true,否则返回false</returns>
|
||
public static bool IsNewDay()
|
||
{
|
||
DateTime currentDate = DateTime.Now.Date;
|
||
bool isNew = currentDate > _lastCheckDate;
|
||
|
||
if (isNew)
|
||
{
|
||
_lastCheckDate = currentDate;
|
||
SaveLastCheckDate(); // 更新并保存新日期
|
||
}
|
||
|
||
return isNew;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 强制重置日期记录(用于测试或特殊场景)
|
||
/// </summary>
|
||
public static void Reset()
|
||
{
|
||
_lastCheckDate = DateTime.MinValue.Date;
|
||
SaveLastCheckDate();
|
||
}
|
||
|
||
private static string orderPath = Path.Combine(Application.streamingAssetsPath, "Order");
|
||
|
||
public static void SaveOrderID(string orderMsg)
|
||
{
|
||
IsNewDay();
|
||
|
||
string dateString = File.ReadAllText(_dateFilePath).Trim();
|
||
string path = Path.Combine(orderPath, $"OrderID{dateString}.txt");
|
||
if (!Directory.Exists(orderPath))
|
||
{
|
||
Directory.CreateDirectory(orderPath);
|
||
}
|
||
|
||
if (!File.Exists(path))
|
||
{
|
||
File.Create(path).Close();
|
||
}
|
||
|
||
var context = File.ReadAllText(path);
|
||
if (string.IsNullOrEmpty(context))
|
||
context = $"{orderMsg}";
|
||
else
|
||
context += $"\n{orderMsg}";
|
||
File.WriteAllText(path, context);
|
||
}
|
||
} |