I wrote this code. But I want to ignore time, I want to compare only day.
from s in sayac_okumalari
where s.okuma_tarihi == startDate && s.sayac_id == sayac_id
group s by new { date = new DateTime(((DateTime)s.okuma_tarihi).Year, ((DateTime)s.okuma_tarihi).Month, ((DateTime)s.okuma_tarihi).Day, ((DateTime)s.okuma_tarihi).Hour, 1, 1) } into g
select new
{
okuma_tarihi = g.Key.date,
T1 = g.Sum(x => x.toplam_kullanim_T1),
T2 = g.Sum(x => x.toplam_kullanim_T2),
T3 = g.Sum(x => x.toplam_kullanim_T3)
};
for example:
25.02.1987 == 25.02.1987
use s.okuma_tarihi.Value.Date == startDate.Date. This should allow you to compare only the Date component.
Update From the discussion in comments looks like the user is using NullableType. Hence updated the solution for NullableType.
Use Date property of DateTime. For ex,
var date= DateTime.Now.Date;
Because you could convert s.okuma_tarihi to DateTime, I think you could do:
var sonuc = from s in sayac_okumalari
where (DateTime)s.okuma_tarihi.Date == startDate.Date && s.sayac_id == sayac_id
group s by new { date = new DateTime(((DateTime)s.okuma_tarihi).Year, ((DateTime)s.okuma_tarihi).Month, ((DateTime)s.okuma_tarihi).Day, ((DateTime)s.okuma_tarihi).Hour, 1, 1) } into g
select new
{
okuma_tarihi = g.Key.date,
T1 = g.Sum(x => x.toplam_kullanim_T1),
T2 = g.Sum(x => x.toplam_kullanim_T2),
T3 = g.Sum(x => x.toplam_kullanim_T3)
};
Hope it helps.
Try using the Date property on the DateTime Object will be a good a simple solution.
string AdmissionDate = "10/15/2017" // mm/dd/yyyy
string DepartureDate = "10/14/2017" // mm/dd/yyyy
if (Convert.ToDateTime(AdmissionDate).Date > Convert.ToDateTime(DepartureDate).Date)
{
// Validation: Admission Date can not be greater than Departure Date...
}
Try this...
try
{
DateTime Date1= DateTime.ParseExact(txtBox1.Text,"dd/MM/yyyy",null);
DateTime Date2 = DateTime.ParseExact(txtBox2.Text, "dd/MM/yyyy", null);
if (Date1 > Date2)
{
//........
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Related
I am trying to replicate the below SQL in C# & Linq , but I am not too experienced with Linq beyond the basics.
SELECT SUM(coalesce(cd.minutesspent,0))
FROM timelabels t
LEFT JOIN challengedetails cd on cd.createddate = t.date
GROUP BY t.date
This would give me a sum of minutes for every date, or zero if there were null entries. Pretty straightforward I think.
// timelabels structure
DateTime start = DateTime.Now.AddDays(-14);
DateTime end = DateTime.Now;
List<DateTime> timelabels = new List<DateTime>();
for (var dt = start; dt <= end; dt = dt.AddDays(1))
{
timelabels.Add(dt);
}
// ChallengeDetails structure & sample data
class ChallengeDetails(){
DateTime? Createddate
int? MinutesSpent
}
List<ChallengeDetails> ChallengeDetails = new List<ChallengeDetails >();
List<ChallengeDetails> ChallengeDetails = new List<ChallengeDetails>();
ChallengeDetails.Add(new ChallengeDetails { MinutesSpent = 44, Createddate = DateTime.Now.AddDays(-10) });
ChallengeDetails.Add(new ChallengeDetails { MinutesSpent = 31, Createddate = DateTime.Now.AddDays(-7) });
ChallengeDetails.Add(new ChallengeDetails { MinutesSpent = 13, Createddate = DateTime.Now.AddDays(-3) });
ChallengeDetails.Add(new ChallengeDetails { MinutesSpent = 77, Createddate = DateTime.Now.AddDays(-2) });
// The Actual Code
List<string> timedata = (from a in timelabels
join al in ChallengeDetails on a equals al.Createddate into All
from al in All.DefaultIfEmpty()
group al by a into grouped
select grouped.Sum(m => m.MinutesSpent ?? 0).ToString()
).ToList();
Looking at this it should work - I have DefaultIfEmpty which should replicate the left join. Within the Sum I have '?? 0' which should be the fallback for any dates that dont have a ChallengeDetail.
But I get System.NullReferenceException: 'Object reference not set to an instance of an object.'
m was null. I shouldnt have gotten this as I have null entries covered or have I got this all wrong ?
Under the section "Actual Code" just add a parenthesis in Sum function, as below
It should take care of null , even before Sum works.
select grouped.Sum(m => (m.MinutesSpent ?? 0)).ToString()
This will do for you, using LINQ - Lambda Expressions:
var TotalMinutesSpentGroupedList = timelabels
.GroupJoin(challengedetails,
t => date,
cd => createddate,
(t,cd) => new
{
MinutesSpent = cd.minutesspent ?? 0,
CreateDate = cd.createddate ?? DateTime.Now
})
.SelectMany(tcd=> challengedetails.DefaultIfEmpty(),
(t, cd) => new
{
MinutesSpent = cd.minutesspent ?? 0,
CreateDate = cd.createddate ?? DateTime.Now
})
.Select(s => new
{
MinutesSpent = cd.minutesspent ?? 0,
CreateDate = cd.createddate ?? DateTime.Now
})
.GroupBy(g => g.createddate).Select(item => item.Sum(s => s.minutesspent));
I am getting the following error:
System.FormatException: 'String '{ ActualInstallDate = 17/04/2020 09:06:23 }' was not recognised as a valid DateTime.
I have to add that in the database ActualInstallDate is nullable, that's why I'm converting it to string, to 'trick' it. The error comes at parsing actualInstallDates. Not sure what's wrong here.
Any suggestion is highly appreciated.
var actualInstallDates = _context.Units.Where(u => u.ID == unitID)
.Select(u => new {
u.ActualInstallDate
}).Single().ToString();
if (actualInstallDates != null)
{
DateTime actualInstallDate = DateTime.ParseExact(actualInstallDates, "dd/MM/yyyy", CultureInfo.InvariantCulture);
var nowString = DateTime.Now.ToString("dd/MM/yyyy");
DateTime now = DateTime.ParseExact(nowString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
var averageWorkOver = (Math.Ceiling(Math.Ceiling(Convert.ToDecimal(now - actualInstallDate)) / 1000 * 60 * 60 * 24) / workOverList.Count).ToString();
ViewBag.AverageWorkOver = averageWorkOver;
}
[Column(TypeName = "datetime2")]
[Display(Name = "ActualInstallDate", Description = "ActualInstallDate_Description", ResourceType = typeof(Resource.Models.Unit))]
public DateTime? ActualInstallDate { get; set; }
You did'nt specify time in the format string. You can either truncate the time part from the date string or add time to the format string.
something like this:
DateTime actualInstallDate = DateTime.ParseExact(actualInstallDates, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
First of all you don't need to select it into anonymous object (if ActualInstallDate is string in database):
var actualInstallDates = _context.Units
.Where(u => u.ID == unitID)
.Select(u => u.ActualInstallDate)
.SingleOrDefault();
if (actualInstallDates != null)
{...}
If you still want to, the don't call ToString on it:
var actualInstallDates = _context.Units.Where(u => u.ID == unitID)
.Select(u => new { u.ActualInstallDate })
.Single();
if (actualInstallDates.ActualInstallDate != null)
{
DateTime.ParseExact(actualInstallDates.ActualInstallDate ...)
...
}
Secondary your date format does not match with the string, try using
DateTime.ParseExact(actualInstallDates, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture)
UPD
Since your field is DateTime? it seems that you've been missing Value property on Nullable<> struct so you just need to fetch your date from db and use actualInstallDates.Value:
var actualInstallDates = _context.Units
.Where(u => u.ID == unitID)
.Select(u => u.ActualInstallDate)
.Single()
if (actualInstallDates != null)
{
var averageWorkOver = (Math.Ceiling(Math.Ceiling(Convert.ToDecimal(DateTime.Now - actualInstallDates.Value)) / 1000 * 60 * 60 * 24) / workOverList.Count).ToString();
ViewBag.AverageWorkOver = averageWorkOver;
}
using (DataAccessAdapter adapter = new DataAccessAdapter())
{
LinqMetaData meta = new LinqMetaData(adapter);
var datas = (from x in meta.Table
where x.DateCreated >= startDate && x.DateCreated <= endDate && x.ViaTo > 0 && !x.Cancelled
group x by new { month = x.DateCreated.Value.Month } into g
select new
{
MonthNr = g.Key,
//MonthName = ?
TotalMonthAmount = g.Sum(x => x.Amount)
});
.....
}
And startDate & endDate are valid Dates.
I only get the month number, how to get the month name for the DateCreated?
You can get the month name using this function:
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthNumber);
new { month = x.DateCreated.Value.Month.ToString("MMM") }
I think you are asking about Month property. Check this:
using System;
class Program
{
static void Main()
{
DateTime now = DateTime.Now;
//
// Write the month integer and then the three-letter month.
//
Console.WriteLine(now.Month); //outputs 5
Console.WriteLine(now.ToString("MMM")); //outputs May
}
}
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
I've two dates
21/01/2011 [From Date]
25/01/2011 [To Date]
How can I get all the dates between these ranges using c#
The answer should be
21/01/2011 22/01/2011
23/01/2011 24/01/2011
25/01/2011
var allDates = Enumerable.Range(0, int.MaxValue)
.Select(x => fromDate.Date.AddDays(x))
.TakeWhile(x => x <= toDate.Date);
I'm sure this can help you:
http://geekswithblogs.net/thibbard/archive/2007/03/01/CSharpCodeToGetGenericListOfDatesBetweenStartingAndEndingDate.aspx
var dateArr = new List<DateTime>();
for (var date = startDate; date <= endDate; date = date.AddDays(1)) {
dateArr.Add(date);
}
Now dateArr contains your required dates.
public System.Collections.Generic.IEnumerable<DateTime> GetDatesBetween(
DateTime start,
DateTime end
)
{
DateTime current = start;
while (current <= end)
{
yield return current.Date;
current = current.AddDays(1);
}
}
should do the job
[edit] Added the .Date to "round" the date to midnigth
How about:
var startDT = new DateTime(2011, 01, 21);
var endDT = new DateTime(2011, 01, 25);
var workDT = startDT;
do
{
Console.WriteLine(workDT.ToString("dd/MM/yyyy"));
workDT = workDT.AddDays(1);
} while (workDT <= endDT);
Console.ReadLine();
I dont know if we have anything to do this inbuilt in Framework but you can try this:
DateTime dt1 = new DateTime(2011,01,21);
DateTime dt2 = new DateTime(2011,01,25);
List<DateTime> datetimerange = new List<DateTime>();
while(DateTime.Compare(dt1,dt2) <= 0)
{
datetimerange.Add(dt1);
dt1 = dt1.AddDays(1);
}
if (toDate < fromDate)
return;
var days = (new DateTime[(toDate - fromDate).Days + 1).
Select((x, i) => fromDate.AddDays(i));