2

これが私のコードです:

DateTime startDate = Convert.ToDateTime( orderDate ).AddMonths(-1);
DateTime endDate = Convert.ToDateTime( orderDate );

orderDateは、私が渡した有効な日付です。

startDateがorderDateの前月の最初の日であることを常に保証するにはどうすればよいですか?endDateがorderDateの月末日であることを常に保証するにはどうすればよいですか?

例:

orderDate = 5/4/2012

I want startDate to be 4/1/2012 (or 04/1/2012 whichever is default)
I want endDate to be 4/30/2012

どうすればこれを達成できますか?

4

5 に答える 5

2
DateTime startDate = Convert.ToDateTime( orderDate ).AddMonths(-1);
// set to first of month
startDate = startDate.AddDays(1-startDate.Day);

// Set end date to last of month, which is one day before first of next month
DateTime endDate = startDate.AddMonths(1).AddDays(-1);
于 2012-05-04T21:14:25.297 に答える
1
origDate = startDate.AddMonths(-1);
DateTime myDate = new DateTime(origDate.Year, origDate.Month, 1);

http://msdn.microsoft.com/en-us/library/xcfzdy4x.aspx

このようなもの...私たちは、日付に拡張メソッドを作成したばかりであることが十分に頻繁に行われます。

于 2012-05-04T21:11:43.827 に答える
1
DateTime startDate = new DateTime( orderDate.Month == 1 ? orderDate.Year - 1 : orderDate.Year, orderDate.Month - 1, 1);
DateTime endDate = new DateTime(orderDate.Year, orderDate.Month, DateTime.DaysInMonth(orderDate.Year, OrderDate.Month));
于 2012-05-04T21:11:52.560 に答える
0

年、月、日などごとに個別の値を取得するDateTimeコンストラクターを使用し、それに応じて調整します(つまり、月の最初は日= 1を意味します)。

于 2012-05-04T21:12:28.990 に答える
0
var orderDate = DateTime.Now.Date;
var endDate = orderDate.AddDays(-orderDate.Day);
var startDate  = endDate.AddDays(-(endDate.Day - 1));
于 2012-05-04T21:23:44.093 に答える