在c#(asp.net)中检查月份是否在间隔中

本文关键字:是否 检查 asp net | 更新日期: 2023-09-27 18:29:17

我正在开发一个应用程序,用户可以在其中下载各种报告。每个月有一个报告,每个报告称为"YYYY-MM.txt"。用户只能下载最近18个月的文件。

我已经编写了一个函数,它接受参数一个文件路径列表,然后将它们下载到客户端。我的问题是如何在这个列表中添加文件,基本上我如何检查一个文件是否在过去18个月内,知道我有他的年份和月份,以及当前的年份和月份。

这就是我所拥有的:

 //just for test, supposed that theses values were extracted from the report of august 2014.
        string fileYear = "2014";
        string fileMonth = "08";
        string currentYear = DateTime.Now.Year.ToString();
        string currentMonth = DateTime.Now.Month.ToString();

我如何将fileYear和fileMonth与currentYear和currentMonth进行比较,以了解报告是否对应于最近18个月。

提前感谢您的帮助

在c#(asp.net)中检查月份是否在间隔中

以下是我的操作方法。

int fileYear = int.Parse(fileName.Substring(0,4));
int fileMonth = int.Parse(fileName.Substring(5,2));
DateTime oldestDate = DateTime.Now.AddMonths(-18);
int oldestYear = oldestDate.Year;
int oldestMonth = oldestDate.Month;
if(fileYear > oldestYear || (fileYear == oldestYear && fileMonth >= oldestMonth))
{
    // This file is within 18 months.
}

这意味着,如果今天是2014年12月31日,它将包括2013-06.txt的文件。如果需要,你也可以进行上限检查,以防你有未来日期的文件。

编辑

另一种选择是根据要比较的文件名创建一个DateTime。以下是我如何做到这一点,以确保我正在比较文件月份的最后一天

int fileYear = int.Parse(fileName.Substring(0,4));
int fileMonth = int.Parse(fileName.Substring(5,2));
DateTime fileDate = new DateTime(fileYear, fileMonth, 1).AddMonths(1).AddDays(-1);
DateTime oldestDate = DateTime.Now.AddMonths(-18);
if(fileDate.Date >= oldestDate.Date)
{
    // This file is within 18 months.
}

您可以这样做:

https://dotnetfiddle.net/VORvZr

using System;
public class Program
{
    public static void Main()
    {
        DateTime fileDate = new DateTime(2013, 5, 1);
        DateTime fileDateNewer = new DateTime(2014, 1, 1);
        GetMonthDifference(fileDate);
        GetMonthDifference(fileDateNewer);
    }
    public static void GetMonthDifference(DateTime fileDate)
    {
        DateTime currentDate =  DateTime.Now;
        DateTime eighteenMonthsAgo = currentDate.AddMonths(-18);
        if (eighteenMonthsAgo > fileDate)
            Console.WriteLine("{0} is greater than or equal to 18 months ago", fileDate);
        else
            Console.WriteLine("{0} is less than 18 months ago", fileDate);
    }
}

请注意,如果可以的话,您总是希望尝试使用最能代表数据的对象。例如,如果使用年份,则应使用数字类型,而不是字符串类型。在这种情况下,使用日期。

编辑:

正如在其他答案上发布的评论所指出的那样,如果文件上传/创建时间刚好在18个月左右,则根据日期,您可能会有一些错误空间。你可以做的事情是获得实际的文件创建日期(假设你是创建文件的系统,文件创建的日期与数据所属的月份一致

string fullFilePathAndName = @""; // wherever your file is located
FileInfo fi = new FileInfo(fullFilePathAndName);
DateTime fileCreateDate = fi.CreationTime