DateTime Format yyyymm - c#

I've found every DateTime format you can think of except the one I need: yyyymm. How do I go about getting this?
I have the following code I'm working with:
List <string> routines = new List<string>();
routines.Add("1 - Routine");
routines.Add("6 - Planned Outage");
int year = 2011;
int quarter = 1;
DateTime timeframe = new DateTime(year, (quarter * 3), 01).AddMonths(1);
var results =
(from wo in WORKORDERs
join wot in WORKORDERTYPEs on wo.Wot_oi equals wot.Wotyoi
join pri in PRIORITies on wo.Prio_oi equals pri.Priooi
join s in SITEs on wo.BEparn_oi equals s.Siteoi
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") &&
!wot.Id.Contains("stand") && !(wo.Ci_cnc_date != null && pri.Prioid != "1 - Routine" &&
pri.Prioid != "6 - Planned Outage") && (SqlMethods.Like(pri.Prioid, "1%") ||
SqlMethods.Like(pri.Prioid, "2%") || SqlMethods.Like(pri.Prioid, "3%"))
select new {PM = wo.Wosource, Site = s.Id, Priority = pri.Prioid, Worktype = wot.Id,
WoNumber = wo.Id, Description = wo.Aenm, CreateDate = wo.Audt_created_dttm,
CloseDate = wo.Clsdt_date,
MonthNum = String.Format("{0:yyyy mm}", wo.Clsdt_date),
Planning = routines.Contains(pri.Prioid) ? "Planned" : "Unplanned"});
I tried using:
MonthNum = String.Format("{0:yyyy mm}", wo.Clsdt_date)
and that gives me the year correctly but the months are all 00. I'm guessing this is because the format for wo.Clsdt_date is different than my string format (it's mm/dd/yyyy).
Any ideas?

You need MM, not mm. mm is minutes.

"mm" is for minutes, "MM" is for Month, but with 2 digits of month. So in June 2012 you will have 201206, however if you need only one digit for month, you can use one "M" instead "yyyyM" and you will get 20126
DateTime.Now.ToString("yyyyMM")

In date formatting, mm means minutes, not months. Use MM instead.

Related

how to combine and convert two integer columns to datetime lambda c#

i have 2 int column in sql database one for month and one for year
i want to query this against Database like this
DateFrom is dateTime and also DateTo is DataTime
var result = GetAll().Where(x =>
(x.InvoiceMonth >= DateFrom.Month && x.InvoiceYear >= DateFrom.Year)
&&
(x.InvoiceMonth <= DateTo.Month && x.InvoiceYear <= DateTo.Year));
but the problem here if user sent 1/1/2021 to 1/1/2023
it will just return Jan 2021 and Jan 2022and Jan 2023
the correct return should return all things between 2 dates
You can construct the date with the data you have
var result = GetAll().Where(x =>
(new DateTime(x.InvoiceYear, x.InvoiceMonth, 1) >=
new DateTime(DateFrom.InvoiceYear, DateFrom.InvoiceMonth, 1))
&&
(new DateTime(x.InvoiceYear, x.InvoiceMonth, 1) <=
new DateTime(DateTo.InvoiceYear, DateTo.InvoiceMonth, 1)));

Linq searches for recent birthdays (within 15 days)

How to use Linq
A table
Field Birthday
Linq searches for recent birthdays (within 15 days)
from a in Employee where a.PositionStatus == true select new{ a.Name,a.Birthday}
Try below query
var fromdate = DateTime.Now;
var todate = DateTime.Now.AddDays(15);
var result =
(
from a in Employee
where a.PositionStuats==true && a.DateOfBirth.Value.Month >= fromdate.Month &&
a.DateOfBirth.Value.Month <= todate.Month &&
a.DateOfBirth.Value.Day >= fromdate.Day && a.DateOfBirth.Value.Day <= todate.Day
select new{ a.Name,a.Birthday}
).ToList();
Depending on your entity frame work version you can also replace a.DateOfBirth.Value.Month with a.DateOfBirth.Month.

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());
}
}

Creating a LINQ query that will include all entries from the current week excluding today and yestreday

I am working on a LINQ query to retrieve all records from the current week, however, I need to exclude any records from today and yesterday.
Here is what I have so far:
DateTime startThisWeek = DateFunctions.GetFirstDayOfWeek(DateTime.Now).AddDays(1);
DateTime endOfThisWeek = startThisWeek.AddDays(6);
DateTime today = DateTime.Now;
DateTime yesterday = DateTime.Now.AddDays(-1);
var notificationList =
(from n in db.DashboardNotifications
.OrderByDescending(n => n.NotificationDateTime)
where (n.NotificationDateTime >= startThisWeek &&
n.NotificationDateTime <= endOfThisWeek) &&
(n.NotificationDateTime != today &&
n.NotificationDateTime != yesterday)
select n).ToList();
The problem with above query is that it is not returning proper records , it also showing todays records too.
Assume your DateFunctions.GetFirstDayOfWeek works correctly
DateTime startThisWeek = DateFunctions.GetFirstDayOfWeek(DateTime.Now);
DateTime yesterday = DateTime.Today.AddDays(-1);
var notificationList =
(from n in db.DashboardNotifications
where n.NotificationDateTime.Date >= startThisWeek.Date &&
n.NotificationDateTime.Date < yesterday)
orderby n.NotificationDateTime descending
select n).ToList();
Comments: If start of current week is not before yesterday, then you will simply get no records. Otherwise yesterday always will be before current week end.
How to get start of week correctly:
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime date,
DayOfWeek startOfWeek = DayOfWeek.Monday)
{
DateTime result = date;
while (result.DayOfWeek != startOfWeek)
result = date.AddDays(-1);
return result.Date;
}
}
You are only excluding records for today and yesterday if they have the same time as when you run the report.
Try
DateTime startThisWeek = DateFunctions.GetFirstDayOfWeek(DateTime.Now.Date).AddDays(1);
DateTime endOfThisWeek = startThisWeek.AddDays(6);
DateTime today = DateTime.Now.Date;
DateTime yesterday = DateTime.Now.Date.AddDays(-1);
var notificationList =
(from n in db.DashboardNotifications
.OrderByDescending(n => n.NotificationDateTime)
where (n.NotificationDateTime >= startThisWeek &&
n.NotificationDateTime.Date <= endOfThisWeek) &&
(n.NotificationDateTime.Date != today &&
n.NotificationDateTime.Date != yesterday)
select n).ToList();
This is assuming that it is possible to have future notifications.
Ps, I'm not sure what the DateFunctions.GetFirstDayOfWeek method does nor why you are adding 1 day to it.

Getting number of records by date in LINQ to SQL query even if no results

I have written the following LINQ-to-SQL to enable me to get a total number of records by day.
There are a few modifications I'd like to make to it in order to have it fit my needs. I have made various attempts but haven't been able to get it right.
I'd like to list the last 9 days, even if there were no 'opens' during this time.
I'd also like to group by Day/Month instead of just Day as I'm doing below.
An example of the output I'd love to get would be:
DateString Opens
===================
9/5 0
10/5 0
11/5 3
etc...
public List<OpensOverTimeViewModel> GetOpensOverTimeViewModel(int eId)
{
DateTime lastDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(-9);
DateTime currentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(1);
var summary = (from p in db.Opens
where (p.ElementId == eId) && (p.Timestamp >= lastDate) && (p.Timestamp <= currentDate)
let k = new
{
Day = p.Timestamp.Day
}
group p by k into t
select new OpensOverTimeViewModel
{
DateString = t.Key.Day,
TotalOpens = t.Count(),
ElementName = ""
}).ToList();
return summary;
}
Any help on how best to tackle this would be much appreciated.
You can create a left join in code after you got the result back from the database
Put the below lines just before your return summary; line.
var allDates = from idx in Enumerable.Range(0, (currentDate - lastDate).Days)
select lastDate.AddDays(idx);
summary = (
from allDate in allDates
join su in summary on allDate.Day equals su.DateString into x
from su in x.DefaultIfEmpty()
select new OpensOverTimeViewModel
{
DateString = allDate.Day,
TotalOpens = su == null ? 0 : su.TotalOpens,
ElementName = ""
}).ToList();
To group by day/month I suggest using the whole date, replacing t.Key.Day with t.Key.Date and changing DateString into a DateTime.

Categories