Week of year translation between c# and SQL - c#

So I'm at the end of a long programming binge and I have one logical hurdle left to get over. My application presents KPIs for quote requests. The business leads have asked for these KPIs to be broken down by week, and I imagine when that is complete the request will come for a breakdown by month. I've figured this out in my SQL queries:
SELECT qpid FROM cpkpis WHERE DATEPART(ww, qpvalidfrom)=13 GROUP BY qpid;
Which will give my a list of qpids to compute a total from and provide actual primary keys for drill down.
What I can't get my head around is how to get an enumeration of weeks of the year form my C# code. I've looked the GregorianCalandar Class and specifically the GetWeekOfYear Method but I'm having trouble coming up with an enumeration of those values.
My question then is this: given a date range [lets say 2013-01-14 through 2013-04-10] how would I get an enumeration of the weeks of the year as ints between the start date and end date?

To help with with this task and the other requirements you're anticipating, you need a date table. IMHO the hardest thing to do in a database is to query data that isn't there.
You can query the date table:
Select Distinct DatePart(ww, dateField) as WeekNo
from DateTable
where dateField between '2013-01-14' and '2013-04-10';

From C#, an iterator is probably the simplest option:
public static IEnumerable<int> WeekNumbersBetween(
DateTime startDate,
DateTime endDate,
Calendar calendar = null,
CalendarWeekRule weekRule = CalendarWeekRule.FirstDay,
DayOfWeek firstDayOfWeek = DayOfWeek.Sunday)
{
if (calendar == null)
{
calendar = new GregorianCalendar();
}
DateTime week = startDate;
while (week <= endDate)
{
yield return calendar.GetWeekOfYear(week, weekRule, firstDayOfWeek);
week = week.AddDays(7);
}
}
The default values for the weekRule and firstDayOfWeek parameters should match the default settings in SQL. If your settings are different, you'll need to specify the correct values.

In T-SQL you could use something like:
DECLARE #StartDate DATE = '2013-01-14';
DECLARE #EndDate DATE = '2013-04-10';
WITH weekcte AS
(SELECT DATEADD(dd, -1, DATEADD(wk, DATEDIFF(wk, 0, #StartDate), 0)) AS DateValue
UNION ALL
SELECT DATEADD(wk, 1, DateValue)
FROM weekcte
WHERE DATEADD(wk, 1, DateValue) <= #EndDate )
SELECT DATEPART(ww, w.DateValue) AS 'Week No'
FROM weekcte AS w;

Related

C# sequence number issue in database

I have a column in the database table i.e. transaction Id. Its data type is var char(50). Now I want to save a row by combining the current date with a sequential number generated.
For Example 10/9/2016 is the date so first transaction is saved like 10920161 and the next one like 10920162 and so on. The sequential number is reset to 1 after every day.
How can I do this?
In SQL Server, it can be as simple as:
transactionId =
CONCAT(DATEPART(MONTH, GETDATE()),
DATEPART(DAY, GETDATE()),
DATEPART(YEAR, GETDATE()),
(SELECT COUNT(1)
FROM tableName
WHERE CONVERT(DATE, dateColumn) = CONVERT(DATE, getdate())) + 1)
Get the Number of transactions for that date, and add one to it. Concat that with a formatted string of Today's Date.
If you already have 3 records for today's date, the result would be:
100920164
Running SQL-Fiddle
Edit: EF suggested snippet:
string dateStr = DateTime.Today.ToString("Mdyyyy");
DateTime todayMidnight = DateTime.Today;
DateTime tomorrowMidnight = DateTime.Today.AddDays(1);
obj.transactionId = dateStr +
context.tableName.Count(x=> x.dateColumn >= todayMidnight
&& x.dateColumn < tomorrowMidnight) + 1;

UTC in DB confusion when querying in linq from Web API server

I can really use some help wrapping my head around a problem I'm having querying data according to a SQL Date field.
I am storing the Date in UTC format using the following code:
objFitCalendarDto.Day = objFitCalendarDto.Day.ToUniversalTime();
That line assigns the date to the model that is inserted into the db through Entity Framework.
Now, my query is supposed to retrieve a row based on a date. So, I should be able to get the row for today, tomorrow, yesterday, and so on.
To do this, I'm using the method to search between two dates, a start date and an end date as follows:
DateTime dayBegin = DateTime.Today.Date.AddDays(dayOffset);
DateTime dayEnd = DateTime.Today.Date.AddDays(dayOffset + 1);
The purpose of dayOffset is to specify which day. If Offset is 0, then I am searching for Today. If dayOffset is 1, then I am searching for rows with tomorrow's date.
Now, since I stored the data originally in UTC, I am assuming that I must search for it in UTC as well. So before executing my query, I convert the dates to UTC like so:
dayBegin = TimeZoneInfo.ConvertTimeToUtc(dayBegin);
dayEnd = TimeZoneInfo.ConvertTimeToUtc(dayEnd);
Then I execute my query like so:
var query = (from f in Db.FitCalendars
where f.FitProgramId == programId &&
f.DayAsDate >= dayBegin && f.DayAsDate < dayEnd
select f);
problem is, it doesn't work. I have a row with the date, "2016-01-26" when I look at it in SQL Manager. However, it only returns from a query on yesterday's date. Today is 2016-01-26, by the way. Clearly I'm not getting this UTC concept. Can anyone see what I'm doing wrong here? I was assuming that if I stored everything as UTC and then before querying I converted my dates for the query to UTC, that everything should work.
UPDATE
Let's try like this:
As soon as you are storing only date part (SQL 'date' type), you
need to compare also only dates.
Instead of
DateTime dayBegin = DateTime.Today.Date.AddDays(dayOffset);
dayBegin = TimeZoneInfo.ConvertTimeToUtc(dayBegin);
let's just do
DateTime dayBegin = DateTime.UtcNow.Date.AddDays(dayOffset);
dayBegin in that case will be date with time anyway (time is 12:00:00 AM). It means, we need to truncate it with DbFunctions. We need equality check here.
var query = (from f in Db.FitCalendars
where f.FitProgramId == programId &&
f.DayAsDate == DbFunctions.TruncateTime(dayBegin)
select f);
END OF UPDATE
I believe that problem is that you comparing dates with times. In your case you need to compare only dates, as far as I understand. As a solution - use DbFunctions TruncateTime function. It can be used within linq queries - like in your code.
https://msdn.microsoft.com/en-us/library/system.data.entity.dbfunctions.truncatetime(v=vs.113).aspx
So, complete solution would be
var query = (from f in Db.FitCalendars
where f.FitProgramId == programId &&
DbFunctions.TruncateTime(f.DayAsDate) >= DbFunctions.TruncateTime(dayBegin) && DbFunctions.TruncateTime(f.DayAsDate) < DbFunctions.TruncateTime(dayEnd)
select f);

How to get records between same date in SQL Server

When I define a "from" and "to" date to be the same value, the query is not returning any rows. When I select an extra day for the "to" date, then rows are returned.
string FrmDt = frmtx.Text.Trim();// 9/1/2015
string ToDt = totx.Text.Trim();//9/1/2015
select
rn.*,
(select count(reue) as RequtNo
from tblests
left join aspne u on r.custorid = u.userid
left join aspnethip a on u.Used=a.UserId
where
u.refere = rn.refid
and r.Compy = 'bbb'
and create >= '9/1/2015'
and create <= '9/1/2015') as refcount
from
tbl_reference rn
Datatype: [Createte] [datime] NOT NULL
How to convert 9/1/2015 12:00:00 AM to 9/1/2015 11:59:59 PM ?
You can simply use it like this:
createdate >= '9/1/2015 00:00:00'and createdate <= '9/1/2015 23:59:59'
or else you can switch to the next day and remove the = from <=
createdate >= '9/1/2015'and createdate < '9/2/2015'
To add time to your date you can try like this:
DateTime frmDt = new DateTime(2015, 09, 01); //time is 00:00:00 by default
DateTime toDt = new DateTime(2015, 09, 01);
TimeSpan toDtTime = TimeSpan.Parse("23:59:59");
DateTime toDtFinal = toDt.Add(ToDtTime);
Convert(date,StartTime) >= '2022-09-1' and Convert(date,EndTime) <= '2022-12-02'
It woked for me when I converted it to date from datetime.
Since your createdate field is a datetime and you define your date stating the date only, the time defaults to 00:00:01. You have three options to deal with that:
Set the range to 9/1/2015 - 9/2/2015, which would select whole 24
hours of 9/1/2015
Set the time explicitly to like 00:00:01 and 23:59:59 respectively like 'YYYY-MM-DD HH:MM:SS' (see https://dev.mysql.com/doc/refman/5.7/en/datetime.html for examples).
Do not define a range at all. Simply search for entries from a specific day like this:
...WHERE DATE(createdate) = '2015-09-01' ...
BTW: in MySQL you define dates as YYYY-MM-DD, so your '9/1/2015' should be '2015-09-01' in fact.
You can also use this way:
declare #tempDate datetime = '2015-09-01'
declare #endDate datetime = DATEADD(SECOND, -1, DATEADD(DAY, 1, #tempDate))
Here #tempDate os your current date. Now how #endDate is calculated, just add 1 day to #tempDate, then subtract 1 second from that, so you will get the today's date with max time. Now you can simply write query to get date between these two dates.
This works fine. Replace the hard coded date to the date column
string FrmDt = frmtx.Text.Trim();// 9/1/2015
string ToDt = totx.Text.Trim();//9/1/2015
select
rn.*,
(select count(reue) as RequtNo
from tblests
left join aspne u on r.custorid = u.userid
left join aspnethip a on u.Used=a.UserId
where
u.refere = rn.refid
and r.Compy = 'bbb'
AND (YEAR('9/1/2015')=2015 AND MONTH('9/1/2015')= 9 AND DAY('9/1/2015')=1)
--and create >= '9/1/2015'
--and create <= '9/1/2015') as refcount
from
tbl_reference rn
If you dont want to change the query like me, I added this in C# in code behind,
DateTime from =Convert.ToDateTime(_dataRange[0]);
DateTime to =Convert.ToDateTime(_dataRange[1]);
if (from == to)
{
to = to.AddHours(23.99); //this gives me 11:59PM in same date
}

Get records of last week adding by datetime in database

I'm using asp.net MVC in my project. My database table includes some records. The table has datetime column for records. I want to get records of last week adding. So the LastlyRecords is:
DateTime.Now = 04.04.2015
LastWeekDateTime = 28.04.2015
LastWeekDateTime < LastlyRecords < DateTime.Now
Have a method that accepts a "Start Date" and "End Date" as parameters.
Call it with a start/end date like:
GetRecords(DateTime.Now.AddWeeks(-1), DateTime.Now);
For there, you can have a stored procedure fetch records between that date range (or do something similar for Entity Framework or whatever you're using).
You can do something similar in T-SQL via GETDATE() and DATEADD(), but it's arguably better to do the range calculation in the calling code (because it's more a business logic thing than a data access thing).
you have to write logic on your query or you can modify below as per your datetime range.
var lastweek = DateTime.Now.AddDays(7);
var records = d in db.Persons
where DateTime.Compare(lastweek, d.DateRecordColumn)
and DateTime.Compare(d.DateRecordColumn, DateTime.Now)
select d;
hope this help to resolve your query!!!
string dateTime = "01 April 2015 Wednesday 16:23";
DateTime time1 = Convert.ToDateTime(dateTime);
if (DateTime.Compare(DateTime.Now, time1) == 1 && // DateTime.Now > time1
DateTime.Compare(time1, DateTime.Today.AddDays((int)-7)) == 1 // time1 >= DateTime.Now-7days
)
{
#("True.")
}
else
{
#("False.")
}
The result is true, so it is in last week.

C# Expressions.How to get Sum (Amount) for last month?

I hava a Transaction datatable with "Amount" field.
I want to get Sum (Amount) for 7 days
How can I do it in C# expression?
Thank you
I assume your transaction table is called 'Transaction' and have a 'Date' field;
DateTime lastWeek = DateTime.Now.Subtract(new TimeSpan(7,0,0,0));
var amountSumLastWeek = (from t in Transaction
where t.Date >= lastWeek
select t.Amount).Sum();
EDIT: Of course const in C# means compile time constant and TimeSpan does not have optional parameters, so I have update the code

Categories