English 中文(简体)
时间操纵
原标题:DateTime manipulation
  • 时间:2012-05-04 21:09:32
  •  标签:
  • c#
  • datetime

我的守则是:

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

命令 日期是我通过的日期。

How do I always guarantee startDate is the first day of the previous month for orderDate? How do I always guarantee endDate is the last day of the month for 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

我怎么能够这样做?

最佳回答
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);
问题回答
origDate = startDate.AddMonths(-1);
DateTime myDate = new DateTime(origDate.Year, origDate.Month, 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));

使用时间构造者,每年、月、日、......采用不同的数值,并对数值进行调整(即月第一日为1日)。

var orderDate = DateTime.Now.Date;
var endDate = orderDate.AddDays(-orderDate.Day);
var startDate  = endDate.AddDays(-(endDate.Day - 1));




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签