简体   繁体   中英

DateTime conversion problems in C#

I have the following SQL snippet:

WHERE YEAR(wo.audt_created_dttm) >= 2011 - 3 --narrows down to a year
AND YEAR(wo.audt_created_dttm) >= 2006 -- bad data less than 2006
AND wo.audt_created_dttm < DATEADD(mm, 1, CAST(CAST(1 * 3 as varchar) + '/01/' +  CAST(2011 as varchar) as DateTime))

which I translated into LINQ to SQL (for testing purposes in LINQPad) like this:

int year = 2012, quarter = 1;
DateTime timeframe = new DateTime(year, (quarter * 3), 01).AddMonths(1); 


where wo.Audt_created_dttm.Value.Year >= year - 3 && wo.Audt_created_dttm.Value.Year >= 2006
    && wo.Audt_created_dttm < timeframe && (s.Id =="NM" || s.Id == "TH") && 
    (wo.Clsdt_date ?? new DateTime(3000, 01, 01)) < DateTime.Now

However, for the actual solution I do not want to specifically define the year or quarter. I want the year and quarter to be current.

For the year, I tried to do this:

DateTime timeframe = new DateTime(timeframe.Year, (quarter * 3), 01).AddMonths(1);

but the compiler doesn't like that at all. Then I tried this:

DateTime setYear = new DateTime();
DateTime timeframe = new DateTime(setYear.Year, (quarter * 3), 01).AddMonths(1)

that didn't work either. I'm at a loss for how to do either the year or the quarter and would appreciate any advice

I want the year and quarter to be current.

To get the first day of the current quarter you can use this code:

var now = DateTime.Now;
var quarter = (now.Month - 1)/3;
var timeframe = new DateTime(now.Year, 3*quarter + 1, 1);

timeframe will contain 2012-04-01, 2012-07-01, 2012-10-01 etc. depending on the current date.

您要今年吗?

  DateTime.Today.Year

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM