2016-04-28 107 views
1

我想在我的web應用程序中計算年份和月份。如何從1月份減去3個月以獲得正確的月份?

在我的代碼中,我有201604年。我想減去3,所以它應該是201601.我得到了這部分工作,但現在如果我想再從201601減去另外3個monyths,結果應該是201511。我不知道如何做到這一點。幫助將不勝感激

代碼

decimal str = "201604"; 
decimal year= (decimal) Calculations.ParseStringToDecimal(str.SubString(0,4), 0); 
decimal month = (decimal) Calculations.ParseStringToDecimal(str.SubString(4,2), 0); 

newMonth = month - 3; 

string newDate = year + month 

//Result: 201601. 

//I want to subtract 201601 again, then the result should be 201511. 
+0

爲什麼不使用datetime類? –

+3

我建議你查看'DateTime'來做日期計算。 – Tom

+2

你需要把你的整數值變成實際的日期,然後'.AddMonths(-3)' – Liam

回答

10

日期使用DateTime類已經用於此目的的工作:

String str = "201604"; 

    DateTime date = DateTime.ParseExact(str, "yyyyMM", CultureInfo.InvariantCulture) 
    .AddMonths(-3); 

    // 201601 
    String newDate = date.ToString("yyyyMM"); 
+0

感謝您的回覆。只是一個問題,我得到了不能使用「DateTime」變量之前它聲明。爲什麼? – RedRocket

+0

@DragonBorn:你的代碼中有一個*語法錯誤*:'DateTime'是* class *,而不是*變量*;你可能會把錯誤的';'像'DateTime;日期'而不是'日期時間日期'。如果你想要一個解決方案,而不僅僅是猜測,請提供你的代碼。 –

+0

謝謝,它現在有效。 – RedRocket

3
string str = "201604"; 
DateTime dateTime = new DateTime(int.Parse(str.Substring(0, 4)), int.Parse(str.Substring(4, 2)), 1); 
dateTime = dateTime.AddMonths(-3); 
string resultString = dateTime.ToString("yyyyMM"); 
4
DateTime threemonthprevDate = DateTime.ParseExact(str,"yyyyMM",CultureInfo.InvariantCulture).AddMonths(-3); 

DateTime sixmonthprevDate = threemonthprevDate.AddMonths(-3)); 

改爲使用ParseExact方法。

1
string str = "201604"; 
decimal year= (decimal) Calculations.ParseStringToDecimal(str.SubString(0,4), 0); 
decimal month = (decimal) Calculations.ParseStringToDecimal(str.SubString(4,2), 0); 
DateTime dateObj = new Date(year, month, 1); 
dateObj.AddMonths(-3); 
//201601 
string newDate1 = dateObj.ToString("yyyyMM"); 
dateObj.AddMonths(-3); 
//201511 
string newDate1 = dateObj.ToString("yyyyMM");