2014-11-05 14 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. 
} 
相關問題