年と月の値を返すフィールドがあります。たとえば、20119 (2011 年は年、9 は 9 月) です。それを現在の年と月と比較して、月の違いを得るにはどうすればよいですか? たとえば、同じ形式で現在の年と月は 20135 になるため、探している値は 20 になります。20135 から 20 か月を引いたものは 20119 になります。月の差を動的に計算する数式を作成する方法がわからないおそらく日付関数を使用します。
9584 次
6 に答える
5
これを試して
DateTime x1 = DateTime.ParseExact("20119", "yyyyM", CultureInfo.InvariantCulture);
DateTime x2 = DateTime.ParseExact("20135", "yyyyM", CultureInfo.InvariantCulture);
int months = Math.Abs((x2.Month - x1.Month) + 12 * (x2.Year - x1.Year));
于 2013-05-08T01:47:43.467 に答える
1
まず、あなたの質問から次のように仮定しています。
- 単一日付の月は 1 桁になります
- Year+Month の値は文字列です (int の場合、以下のコードの in 値で ToString() をスローします)。
したがって、値の長さは 5 ~ 6 桁になります。以下のコードをより少ない行で実行できますが、私の冗長な回答を許してください - これをより明確にするために余分なコードを追加します:
Date.Now を使用して取得することで、現在の日付を月年としてのみ取得できます。
// Just want the month/year
DateTime currentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
これで、部分文字列メソッドを使用して現在の年/月に対してテストする日付を取得できます (文字列値を扱っているという私の仮定を思い出してください。そうでない場合は ToString() を変換します)。
// breaking out test date to year/month portions and saving as a new date time
string testDateValue = "20119";
int testDateYear = Convert.ToInt32(testDateValue.Substring(0, 4));
int testDateMonth = Convert.ToInt32(testDateValue.Substring(4));
DateTime testDate = new DateTime(testDateYear, testDateMonth, 1);
違いを見てみましょう:
// get month dif - remove abs() if want negative if test date in future
int numberOfMonths = Math.Abs(((currentDate.Year - testDate.Year) * 12) +
(currentDate.Month - testDate.Month));
ここで、現在の日付を使用する代わりに yyyym 形式で 2 日を比較する場合は、上記の年/月の変換を行ってから、月の差分式を実行します。
于 2013-05-08T01:55:46.393 に答える
1
各日付フィールドの年に月数を掛けて、その差を返さないのはなぜですか?
于 2013-05-08T01:44:50.460 に答える
0
これは、MSDN (リンク)に投稿されたソリューションのコード スニペットです。
DateTime oldDate = new DateTime(2002,7,15);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = newDate - oldDate;
// Difference in days.
int differenceInDays = ts.Days;
年/月も機能するはずです(次のようなもの):
int differenceInMonths = (ts.Years *12 + ts.Months);
これが役立つことを願っています。Rgds, アルバータ州
于 2013-05-08T01:48:28.197 に答える