2014-11-05 34 views
0

我正在开发一个应用程序,用户可以下载各种报告。每月有一份报告,每份报告称为“YYYY-MM.txt”。用户只能下载过去18个月的文件。检查月份是否在C#中间隔(asp.net)

我已经写了一个函数,它接受参数列表的文件路径,然后将它们下载到客户端。我的问题是如何在这个列表中添加文件,基本上我该如何检查一个文件是否在过去的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

感谢的提前你的帮助

回答

0

你可以做这样的事情:

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 
+0

个人更有意义的假设每月一个文件意味着月底,而不是开始。 – juharr 2014-11-05 13:37:25

+0

同意 - 尽管看起来你会在某个地方做一个假设*。以本月第一天的DateTimes为例。 – Kritner 2014-11-05 13:41:12

1

这是我会怎么做。

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。如果需要的话,你也可以把一个上限检查以防你可能有未来的日期文件。

EDIT

另一种替代方法是从文件名中创建一个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. 
} 
相关问题