Convert only date to Date and Time format in c# - c#

I want to count data of each day from database using the for loop. Here, I don't know to get the begining of day (start from 12 am) and end of that day ( 12 pm) from value of only date. In below code startDate and endDate have only date value e.g. 2/11/2012.
for (DateTime dates = startDate; dates <= endDate; dates.AddDays(1))
{
DateTime BeginingOfDay = begining of value variable dates; // 2/2/2012 00:00:00
DateTime EndOfDay = at end of value variable dates; // 2/2/2012 23:59:59
int count = (from u in db.CDRs where (u.StartTime >= BeginingOfDay && u.StartTime <= EndOfDay) select u).Count();;
dictionary.Add(dates.ToString("MM/dd/yyyy"), count);
}

The best way to deal with this is to use the right combination of lessthan/greaterthan operators with midnight on day n, and midnight on day n+1
so given a day, eg
var date = new Date(2012,8,24); // today
get midnight on that day (start of the day)
var start = new Date(date.Year, date.Month, date.Day, 0,0,0); // could also be date.Date
and to get midnight on the next day just add 1 day
var end = start.AddDays(1);
now use greater-than-or-equal-to for the start, and less-than for the end:
var inRange = x.StartTime>=start && x.EndTime<end
Put together into your example becomes:
for (DateTime dates = startDate; dates <= endDate; dates.AddDays(1))
{
DateTime BeginingOfDay = new DateTime(dates.Year,dates.Month,dates.Day,0,0,0);
DateTime EndOfDay = BeginingOfDay.AddDays(1);
int count = (from u in db.CDRs where (u.StartTime >= BeginingOfDay && u.StartTime < EndOfDay) select u).Count();;
dictionary.Add(dates.ToString("MM/dd/yyyy"), count);
}

This should get you the results you want:
using(var dataContext = new YourDataContext())
{
var dictionary = dataContext.CDRs.GroupBy(u => new
{
u.StartTime.Year,
u.StartTime.Month,
u.StartTime.Day
})
.Select(g => new{ Date = g.Key, Count = g.Count() })
.ToDictionary(g => new DateTime(g.Key.Year, g.Key.Month, g.Key.Day), g=>g.Count);
return dictionary;
}

Related

How do I use an IF statement on a datetime from Dictionary<string, List<datetime>> in C#

The data I am pulling from the database is (string, datetime) and I need to review datetime to see if it equals sysdate today # 14:00, but i can't figure out how to just look at the datetime field from list.
int recordCount;
using (IDatabase db = SystemStatus.GetDatabase(_connectionStrings.stuff))
{
const string query= #"
SELECT DISTINCT string, date
FROM table
WHERE date > DATE_SUB(SYSDATE(), Interval 30 day) AND
drop_date < DATE_SUB(NOW(), Interval 12 hour) AND
status_id = 2;";
var records = db.Fetch<Dictionary<string, List<DateTime>>>(query);
recordCount = records.Count;
}
You need a datetime object for your comparison:
DateTime now = DateTime.Now;
DateTime dt = new DateTime(now.Year, now.Month, now.Day, 14, 0, 0); // 2 PM today
You don't need an "if" statement. You need to use object querying (LINQ)...
using System.Linq;
// get everything past 2 PM today
var after2PMRecords = records.Where(r => r.Value > dt);
// get everything before 2 PM today
var before2PMRecords = records.Where(r => r.Value < dt);

Get data based on two dates values filtered by month

I have list of events, each event has two dates; start date and end date. I want to create a filter by months. How do I return dates that ranges between a month that a user selects?
for example, lets say the user selects month October, I want to return all events that are within this month.
I have used this to get the dates that ranges between todays date but now stuck on how to get the range between a month.
DateTime dateToCheck = DateTime.Today.Date;
DateTime startDate = DateTime.Parse(item["Start Time"].ToString());
DateTime endDate = DateTime.Parse(item["End Time"].ToString());
foreach (SPListItem item in collection)
{
if (startDate <= dateToCheck && dateToCheck < endDate)
{
ListBox1.Items.Add(item["EventTitle"].ToString());
}
}
// set up dummy data
var dates = new[] {DateTime.Now, DateTime.Now, DateTime.Now};
int month = GetMonth();
// get result
var result = dates.Where(date => date.Month == month);
EDIT: if you need to make sure the dates have the correct year as well, use
var dates = new[] {DateTime.Now, DateTime.Now, DateTime.Now};
int year = GetYear();
int month = GetMonth();
var result = dates.Where(date => date.Year == year && date.Month == month);
Of course, you can get the year/month numbers as well as the date-list from wherever.
EDIT2: if you get a DateTime object as input modify accordingly:
var dates = new[] {DateTime.Now, DateTime.Now, DateTime.Now};
var input = GetDateTime();
var result = dates.Where(date => date.Year == input.Year && date.Month == input.Month);
You still can use your code with little modifications. As start date you have to select 00:00 time of 1st of the month and as end date you have to use 00:00 time of 1st of the next month. In case of October 2015 it would be: 1 Oct 2015 <= date < 1 Nov 2015.
int year = 2015;
int month = 10;
DateTime dateToCheck = DateTime.Today.Date;
DateTime startDate = new DateTime(year, month, 1);
DateTime endDate = startDate.AddMonths(1);
foreach (SPListItem item in collection)
{
if (startDate <= dateToCheck && dateToCheck < endDate)
{
ListBox1.Items.Add(item["EventTitle"].ToString());
}
}

Get List of weeks by giving year and month as parameter C#

I need list of weeks with starting and ending dates by giving int year and int month,
Example Result,
Week1 = 7/1/2012 to 7/1/2012
Week2 = 7/2/2012 to 7/8/2012
Week3 = 7/9/2012 to 7/15/2012
Week4 = 7/16/2012 to 7/22/2012
Week5 = 7/23/2012 to 7/29/2012
Week6 = 7/30/2012 to 7/31/2012
Something like this should work:
// using System.Globalization;
var calendar = CultureInfo.CurrentCulture.Calendar;
var firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
var weekPeriods =
Enumerable.Range(1, calendar.GetDaysInMonth(year, month))
.Select(d =>
{
var date = new DateTime(year, month, d);
var weekNumInYear = calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, firstDayOfWeek);
return new { date, weekNumInYear };
})
.GroupBy(x => x.weekNumInYear)
.Select(x => new { DateFrom = x.First().date, To = x.Last().date })
.ToList();
Of course you can change the Culture (here I have used the CurrentCulture).
check this one and edit according to your need
// Get the weeks in a month
DateTime date = DateTime.Today;
// first generate all dates in the month of 'date'
var dates = Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month)).Select(n => new DateTime(date.Year, date.Month, n));
// then filter the only the start of weeks
var weekends = (from d in dates
where d.DayOfWeek == DayOfWeek.Monday
select d).ToList();
foreach (var d in weekends)
{
Console.WriteLine(d);
}
Console.Write(weekends);
Console.ReadLine();
hope it help you.
you can also take a look here for other stuff HERE

Get Date List from weeknumber c#

I have a function that get the current weeknumber from the given date
e.g.
GregorianCalendar cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
return cal.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
gives back weeknumber 40 for DateTime.Now.
So my question is , also my problem, i need to get the dates in the returned week. I've tried several thing and none so for worked.
You can use the class Week of the Time Period Library for .NET:
Week week = new Week( new DateTime( 2012, 03, 21 ) );
Console.WriteLine( "week #: ", week.WeekOfYear );
Console.WriteLine( "week first day: ", week.FirstDayOfWeek );
Console.WriteLine( "week last day: ", week.LastDayOfWeek );
Additional, the class Week supports ISO 8601 week numbering and custom cultures.
You could use this function to get the first date of a week:
public static DateTime FirstDateOfWeek(int year, int weekOfYear)
{
DateTime jan1 = new DateTime(year, 1, 1);
int daysOffset = Convert.ToInt32(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek) - Convert.ToInt32(jan1.DayOfWeek);
DateTime firstWeekDay = jan1.AddDays(daysOffset);
System.Globalization.CultureInfo curCulture = System.Globalization.CultureInfo.CurrentCulture;
int firstWeek = curCulture.Calendar.GetWeekOfYear(jan1, curCulture.DateTimeFormat.CalendarWeekRule, curCulture.DateTimeFormat.FirstDayOfWeek);
if (firstWeek <= 1) {
weekOfYear -= 1;
}
return firstWeekDay.AddDays(weekOfYear * 7);
}
Then you can get all dates in this week in the following way:
var firstDate = FirstDateOfWeek(2012, 40);
var allWeekDays = new List<DateTime>();
allWeekDays.Add(firstDate);
var currentDate = firstDate;
for(int d = 1; d < 7; d++)
{
currentDate=currentDate.AddDays(1);
allWeekDays.Add(currentDate);
}
or in one line:
var week = Enumerable.Range(0,7).Select(d => firstDate.AddDays(d)).ToList();
You can get the first and last day in the week simply by looking at the weekday of the given date, and look for the monday:
DateTime firstDay = date.Date;
while (firstDay.DayOfWeek != DayOfWeek.Monday) {
firstDay = date.AddDays(-1);
}
DateTime lastDay = firstDay.AddDays(6);

Select current week using LINQ

How do I write the where statement that select records with Date field between Sunday to Saturday of a given date.
Data Fields: Id, Name, Date
Where date is the date in question, how about:
DateTime start = date.Date.AddDays(-(int)date.DayOfWeek), // prev sunday 00:00
end = start.AddDays(7); // next sunday 00:00
var qry = from record in data
where record.Date >= start // include start
&& record.Date < end // exclude end
select record;
DateTime givenDate = DateTime.Today;
DateTime startOfWeek = givenDate.AddDays(-1 * givenDate.DayOfWeek);
DateTime endOfWeek = startOfWeek.AddDays(7);
var query = myObjects
.Where(ob => startOfWeek <= ob.DateField && ob.DateField < endOfWeek)

Categories