我试图计算几个月的天数时会得到意想不到的结果。例如,我想确定2018年每个月的第29天。由于2月没有第29天,我预计11个日期:1月29日,3月29日,4月29日等等...相反,我只得到1月29日返回。
粘贴到游乐场:
var calendar = Calendar(identifier: .gregorian)
calendar.locale = Locale(identifier: "en_US")
calendar.timeZone = TimeZone(identifier: "America/Chicago")!
let firstOfYear = Date(timeIntervalSince1970: 1514786400)
let endDate = calendar.date(byAdding: .year,
value: 1,
to: firstOfYear,
wrappingComponents: false)!
var components = DateComponents()
components.day = 29 // unexpected results
// components.day = 5 // correct results
var dates = [Date]()
calendar.enumerateDates(startingAfter: firstOfYear,
matching: components,
matchingPolicy: .strict,
using: { (nextDate: Date?, exactMatch: Bool, stop: inout Bool) in
if nextDate?.compare(endDate) == .orderedDescending {
stop = true
return
}
dates.append(nextDate!)
})
dates
请注意,我尝试了所有4种matchingPolicy
类型的结果。谁能够揭示正在发生的事情?似乎枚举在一个月内找不到日期后停止。最好的做法是创建自己的循环来确定日期吗?
答案 0 :(得分:4)
来自 namespace ShareSize
{
class Program
{
static long Size { get; set; }
static List<Task> Tasks = new List<Task>();
private static Object Lock = new Object();
static void Main(string[] args)
{
string share = "";
using (StreamReader sr = new StreamReader(args[0]))
{
while (!sr.EndOfStream)
{
share = sr.ReadLine().Trim(',');
string[] root = Directory.GetDirectories(share);
MeasureFolders(root).ConfigureAwait(false);
MeasureFiles(Directory.GetFiles(share));
using (StreamWriter sw = new StreamWriter(args[1], true))
{
sw.WriteLine(share + "," + Size / 1073741824);
}
Size = 0;
}
}
Console.ReadLine();
}
private static async Task MeasureFolders(string[] root)
{
await MeasureFolder(root).ConfigureAwait(false);
await Task.WhenAll(Tasks.ToArray());
}
private static async Task MeasureFolder(string[] directories)
{
foreach (string d in directories)
{
try
{
string[] files = Directory.GetFiles(d);
string[] subDirectories = Directory.GetDirectories(d);
if (files.Length != 0)
{
Task newTask = new Task(delegate { MeasureFiles(files); });
newTask.Start();
Tasks.Add(newTask);
}
if (subDirectories.Length != 0)
await MeasureFolder(subDirectories);
}
catch
{
;
}
}
}
private static void MeasureFiles(string[] files)
{
foreach (var f in files)
{
lock (Lock)
{
try
{
Size += new FileInfo(f).Length;
}
catch
{
;
}
}
}
}
}
}
的文档:
如果无法完全匹配,并且使用strict选项请求,则将nil传递给闭包并且枚举结束
这就是为什么你只得到1月29日的日期。在非闰年要求不存在的日期,例如2月29日时,使用其他匹配模式效果不佳。
以下代码为您提供所需的结果:
Calendar enumerateDates