Tables dt like this:
index StartDate EndDate
1 2015/03/23 22:00 2015/03/23 23:00
2 2015/03/23 22:00 2015/03/23 22:00
3 2015/03/23 22:00 2015/03/23 22:00
I have set:
lookupedit1.Properties.ValueMember = "StartDate";
lookupedit1.Properties.DisplayMember = "StartDate";
So, the value has show OK, long date Type, but i want the DisplayMemeber like short date type.
I have try any of below, but it's havn't work expectly.
lookupedit1.Properties.Mask.EditMask = "yyyy-MM-dd";
lookupedit1.Properties.DisplayFormat.FormatString = "yyyy-MM-dd";
lookupedit1.Properties.EditFormat.FormatString = "yyyy-MM-dd";
How can i resolve my questions?
i want the DisplayMemeber like short date type
You can use the standard d display-format string for short date (culture specific, described in the Standard Date and Time Format Strings document in MSDN.). To specify formatting-behavior you should add the specific column into the LookUp edit:
lookUpEdit1.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo()
{
FieldName = "StartDate",
FormatType = DevExpress.Utils.FormatType.DateTime,
FormatString = "d" // short date
});
lookUpEdit1.Properties.DataSource = new List<Order> {
new Order(){ StartDate = new DateTime(2015, 03, 23, 23, 0, 0) },
new Order(){ StartDate = new DateTime(2015, 03, 24, 23, 0, 0) },
new Order(){ StartDate = new DateTime(2015, 03, 25, 23, 0, 0) },
};
To setup display-behavior while editing you can use the editor's Mask :
lookUpEdit1.Properties.Mask.EditMask = "d"; // short date
lookUpEdit1.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.DateTime;
lookUpEdit1.Properties.Mask.UseMaskAsDisplayFormat = true;
Related
I'm trying to make a function in C# that returns the week difference between two dates. Its goal is to provide the same result of:
select datediff(ww,'2018-04-13','2018-04-16') as diff
In the example above there is only 3 days between these dates, but they are in different weeks, so the result should be 1.
I've tried to use .TotalDays but it's not working properly. I also tried .GetWeekOfYear but it won't return correctly when the year of the dates are different. I've seem many questions here on StackOverflow and on other forums and so far none of them match my case. This is the function I'm trying to far:
public static int GetWeekDiff(DateTime dtStart, DateTime dtEnd) {
// Doesn't work
var val = ((dtEnd - dtStart).TotalDays / 7);
val = Math.Ceiling(val);
return Convert.ToInt32(val);
// Doesn't work well between years
DateTimeFormatInfo dinfo = DateTimeFormatInfo.CurrentInfo;
var x = dinfo.Calendar.GetWeekOfYear(dtStart, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
var y = dinfo.Calendar.GetWeekOfYear(dtEnd, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
return y - x;
}
In the first part of my function, I tried what is described in this post. It didn't work
Can you help me?
Thanks in advance.
First figure how many days there are between the two dates. Divide the number of days by 7 to get full weeks.
Now figure out if there's an extra week to be counted by finding taking the number of days modulus 7 to get any remaining days. If the first date plus remaining days falls in a different week, add an extra week on to the count.
void Main()
{
var first = new DateTime(2018, 04, 13);
var second = new DateTime(2018, 04, 16);
Console.WriteLine(weekDiff(first, second));
}
public int weekDiff(DateTime d1, DateTime d2, DayOfWeek startOfWeek = DayOfWeek.Monday)
{
var diff = d2.Subtract(d1);
var weeks = (int)diff.Days / 7;
// need to check if there's an extra week to count
var remainingDays = diff.Days % 7;
var cal = CultureInfo.InvariantCulture.Calendar;
var d1WeekNo = cal.GetWeekOfYear(d1, CalendarWeekRule.FirstFullWeek, startOfWeek);
var d1PlusRemainingWeekNo = cal.GetWeekOfYear(d1.AddDays(remainingDays), CalendarWeekRule.FirstFullWeek, startOfWeek);
if (d1WeekNo != d1PlusRemainingWeekNo)
weeks++;
return weeks;
}
static void Main(string[] args)
{
DateTime date1 = new DateTime(2018, 04, 18);
DateTime date2 = new DateTime(2018, 04, 19);
System.Console.WriteLine((GetDiff(new DateTime(2018, 04, 18), new DateTime(2018, 04, 18)))); // 0
System.Console.WriteLine((GetDiff(new DateTime(2018, 04, 22), new DateTime(2018, 04, 23)))); // 1
System.Console.WriteLine((GetDiff(new DateTime(2018, 04, 16), new DateTime(2018, 04, 22)))); // 0
System.Console.WriteLine((GetDiff(new DateTime(2018, 04, 18), new DateTime(2018, 05, 03)))); // 2
}
private static int GetDiff(DateTime date1, DateTime date2)
{
date1 = SetDayToMonday(date1);
date2 = SetDayToMonday(date2);
return (int)((date2 - date1).TotalDays / 7);
}
private static DateTime SetDayToMonday(DateTime date)
{
var weekDay = date.DayOfWeek;
if (weekDay == DayOfWeek.Sunday)
return date.AddDays(-6);
else
return date.AddDays(-((int)weekDay-1));
}
First, set the day to the monday of the current week. Then count all full weeks(= /7 days as int). Easy as it is, it works probably across weeks and years.
See if this works. There could be more use cases that this doesn't cover, and the solution depends on how you define a week boundary (this assumes Sunday-Monday based on a comment above).
// Output:
// Weeks between 12/28/2017 and 1/10/2018: 2
// Weeks between 4/13/2018 and 4/16/2018: 1
// Weeks between 4/21/2018 and 4/22/2018: 0
// Weeks between 4/22/2018 and 4/23/2018: 1
void Main()
{
var datePairs = new List<KeyValuePair<DateTime, DateTime>>();
datePairs.Add(new KeyValuePair<DateTime, DateTime>(new DateTime(2017, 12, 28), new DateTime(2018, 1, 10)));
datePairs.Add(new KeyValuePair<DateTime, DateTime>(new DateTime(2018, 4, 13), new DateTime(2018, 4, 16)));
datePairs.Add(new KeyValuePair<DateTime, DateTime>(new DateTime(2018, 4, 21), new DateTime(2018, 4, 22)));
datePairs.Add(new KeyValuePair<DateTime, DateTime>(new DateTime(2018, 4, 22), new DateTime(2018, 4, 23)));
foreach (var datePair in datePairs)
{
var string1 = datePair.Key.ToShortDateString();
var string2 = datePair.Value.ToShortDateString();
Console.WriteLine($"Weeks between {string1} and {string2}: {GetWeekDiff(datePair.Key, datePair.Value)}");
}
}
public static int GetWeekDiff(DateTime dtStart, DateTime dtEnd)
{
var totalDays = (dtEnd - dtStart).TotalDays;
var weeks = (int)totalDays / 7;
var hasRemainder = totalDays % 7 > 0;
if (hasRemainder)
{
if (!(dtStart.DayOfWeek.Equals(DayOfWeek.Saturday) && dtEnd.DayOfWeek.Equals(DayOfWeek.Sunday)))
{
weeks++;
}
}
return weeks;
}
Maybe it can help
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
Get the correct week number of a given date
Can't comment yet and already used a flag on this post on something I believed to be similar. Here is another post I found that appears to align with the solution you are trying to create:
Get the number of calendar weeks between 2 dates in C#
This is my implementation to solve a similar problem, I haven't tested in thoroughly but it seems to work.
var dt1 = DateTime.Today.AddDays(-30);
var dt2 = DateTime.Today;
var noOfDays =(int) (dt2 - dt1).TotalDays;
int reminder;
var weeks = Math.DivRem(noOfDays, 7, out reminder);
weeks = reminder > 0 ? weeks + 1 : weeks;
It returns 1 week for 6 days or less gap, which is exactly what I needed.
I am in need of some wizards.
I have a table
Start End PersonID
-----------------------------------------------------
10/07/2017 00:00:00 18/07/2017 00:00:00 1
27/07/2017 00:00:00 27/07/2017 00:00:00 1
28/07/2017 00:00:00 28/07/2017 00:00:00 1
29/07/2017 00:00:00 29/07/2017 00:00:00 1
30/07/2017 00:00:00 30/07/2017 00:00:00 1
If I search for
Date Start = 11/07/2017
Date End = 12/07/2017
Using this query:
DateTime start = new DateTime(2017,07,11,0,0,0,0,0);
DateTime end = start.AddDays(1);
DateTime[] days = new DateTime[end.Subtract(start).Days];
for (int i = 0; i < end.Subtract(start).Days; i++)
{
var d = start.AddDays(i);
days[i] = d;
}
IQueryable block = tmOpen1.Calendar.Where(x => days.All(y => y >= x.start && y <= x.end)).Select(x => new { ID = x.PersonID });`
I get a positive result for ROW 1 (10/07/2017 - 18/07/2017)
However If I apply it against the remaining rows e.g. Filter
Date Start = 28/07/2017
Date End = 29/07/2017
Then obviously this will fail. How Can I get this side of the search to work.
E.g. Either
Take the first row and make it split out into individual rows
Make the Individual rows return true if a Person has several true conditions.
I hope one of the geniuses here can help.
Seems like all you really need is something like this:
DateTime start = new DateTime(2017,07,11,0,0,0,0,0);
DateTime end = start.AddDays(1);
var results = tmOpen1.Calendar
.Where(c => start <= c.end && end >= c.start)
.Select(x => new { ID = x.PersonID });
If your interval starts or ends somewhere between a start and end date from the table, than it means it is overlapping and you should included in your result.
tmOpen1.Calendar.Where(x => (startDate >= x.start && startDate <= x.end) || (endDate >= x.start && endDate <= x.end)).Select(x => new { ID = x.PersonID });
So an interval 10.07 - 27.07 should give you the first 2 rows, right?
Or is the interval supposed to be fully enclosed between 2 dates in the table?
From understanding of your question you want to know when the Date Start or Date End is within a range of dates.
You can check Date Start is within the date range or the Date End is within the date range
Example:
List<DateRange> dates = new List<DateRange>();
dates.Add(new DateRange()
{
StartDate = new DateTime(2017, 07, 10),
EndDate = new DateTime(2017, 07, 18)
});
dates.Add(new DateRange()
{
StartDate = new DateTime(2017, 07, 28),
EndDate = new DateTime(2017, 07, 28)
});
DateRange search1 = new DateRange()
{
StartDate = new DateTime(2017, 07, 11),
EndDate = new DateTime(2017, 07, 12)
};
DateRange search2 = new DateRange()
{
StartDate = new DateTime(2017, 07, 28),
EndDate = new DateTime(2017, 07, 29)
};
var result1 = dates.Where(x => search1.StartDate >= x.StartDate && search1.StartDate <= x.EndDate ||
search1.EndDate <= x.StartDate && search1.EndDate >= x.EndDate);
var result2 = dates.Where(x => search2.StartDate >= x.StartDate && search2.StartDate <= x.EndDate ||
search2.EndDate <= x.StartDate && search2.EndDate >= x.EndDate);
Simplier with the not valid time frame:
DateTime start = new DateTime(2017, 07, 11, 0, 0, 0, 0, 0);
DateTime end = start.AddDays(1);
var results = tmOpen1.Calendar.
.Where( c => ! ( c.Start > end || c.End < start) )
.Select(x => new { ID = x.PersonID } );
For DateTime start = new DateTime(2017, 07, 11, 0, 0, 0, 0, 0);
The result are:
TEST 1: 11/07/2017 00:00:00
Start:10/07/2017 00:00:00 End:18/07/2017 00:00:00 ID:1
For DateTime start = new DateTime(2017, 07, 28, 0, 0, 0, 0, 0);
The result are:
TEST 2: 28/07/2017 00:00:00
Start:28/07/2017 00:00:00 End:28/07/2017 00:00:00 ID:1
Start:29/07/2017 00:00:00 End:29/07/2017 00:00:00 ID:1
modelclassList= modelclassList.Where(x => x.gf_expdate>DateTime.Now).ToList();
to check expiry date and save back list of model class
Given this datetime of January 1 2015 at 23:00 hours:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
And given the int 6, which is the desired hour, how do I return the first following datetime where the hour is 6? In this case, someDate and 6 would return a new DateTime of January 2 2015 at 06:00 hours.
I would simply add the hours to the original date and add another day if the result is before the original time:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddHours(6); // note the "Date" part
if (result < someDate) result = result.AddDays(1);
You just have to add one day to the date and six hours to the result:
var someDate = new DateTime(2015, 1, 1, 23, 0, 0);
var result = someDate.Date.AddDays(1).AddHours(6);
Note the use of Date property - it will give you the start od the day and from there it's easy to navigate forward.
Try this:
while(someDate.Hour != 6){
someDate = someDate.AddHours(1);
}
Assuming you meant 24h clock, you can try this:
public DateTime GetDate(DateTime someDate,int hour)
{
return someDate.Hour>=hour? someDate.Date.AddDays(1).AddHours(6):someDate.Date.AddHours(6);
}
Something like this should do it:
public DateTime FollowingHour(DateTime start, int hour)
{
DateTime atHour = start.Date.AddHours(6);
if(atHour < start)
{
atHour += TimeSpan.FromDays(1);
}
return atHour;
}
I have the requirement to create a query using Linq to Entities where the birthday must fall within 2 days ago and the next 30 days.
The following returns nothing:
DateTime twoDaysAgo = DateTime.Now.AddDays(-2);
int twoDaysAgoDay = twoDaysAgo.Day;
int twoDaysAgoMonth = twoDaysAgo.Month;
DateTime MonthAway = DateTime.Now.AddDays(30);
int monthAwayDay = MonthAway.Day;
int monthAwayMonth = MonthAway.Month;
var bdays = from p in db.Staffs where EntityFunctions.TruncateTime(p.BirthDate) > EntityFunctions.TruncateTime(twoDaysAgo) &&
EntityFunctions.TruncateTime(p.BirthDate) < EntityFunctions.TruncateTime(MonthAway)
orderby p.BirthDate select p;
return bdays;
The problem I'm having is that I need something where if the birthday falls from 11/3 to 12/5, it should return it. The reason it fails because the birthdays include the Year. However, when I use something like:
p.BirthDate.Value.Month
I receive the error that this isn't support with Linq to Entities. Any assistance would be appreciated.
Year-wrapping independent solution:
void Main()
{
var birthdays = new List<DateTime>();
birthdays.Add(new DateTime(2013, 11, 08));
birthdays.Add(new DateTime(2012, 05, 05));
birthdays.Add(new DateTime(2014, 05, 05));
birthdays.Add(new DateTime(2005, 11, 08));
birthdays.Add(new DateTime(2004, 12, 31));
foreach(var date in birthdays.Where(x => x.IsWithinRange(twoDaysAgo, MonthAway))){
Console.WriteLine(date);
}
}
public static class Extensions {
public static bool IsWithinRange(this DateTime #this, DateTime lower, DateTime upper){
if(lower.DayOfYear > upper.DayOfYear){
return (#this.DayOfYear > lower.DayOfYear || #this.DayOfYear < upper.DayOfYear);
}
return (#this.DayOfYear > lower.DayOfYear && #this.DayOfYear < upper.DayOfYear);
}
}
Output with
DateTime twoDaysAgo = DateTime.Now.AddDays(-2);
DateTime MonthAway = DateTime.Now.AddDays(30);
8/11/2013 0:00:00
8/11/2005 0:00:00
Output with
DateTime twoDaysAgo = new DateTime(2012, 12, 25);
DateTime MonthAway = new DateTime(2013, 01, 05);
31/12/2004 0:00:00
If you want to ignore the value of the year, what about using DayOfYear function ?
var bdays = from p in db.Staffs
where EntityFunctions.DayOfYear(p.BirthDate) > EntityFunctions.DayOfYear(twoDaysAgo) &&
EntityFunctions.DayOfYear(p.BirthDate) < EntityFunctions.DayOfYear(MonthAway)
orderby p.BirthDate select p;
You can change all the years to now since year is irrelevant and then you can check it this way
DateTime twoDaysAgo = DateTime.Today.AddDays(-2);
DateTime monthAway = DateTime.Today.AddMonths(1);
List<DateTime> checkDates = new List<DateTime>
{ new DateTime(2011, 11, 3), new DateTime(2011, 12, 5), new DateTime(2011, 12, 6), new DateTime(2011, 11, 2) };
checkDates = checkDates.Select(x => new DateTime(DateTime.Today.Year, x.Month, x.Day)).ToList();
var bdays = from p in checkDates
where (p >= twoDaysAgo && p <= monthAway) ||
(p>= twoDaysAgo.AddYears(-1) && p <= monthAway.AddYears(-1))
orderby p
select p;
This results in
11/3/2013 12:00:00 AM
12/5/2013 12:00:00 AM
This also works with the following list of dates when today is new DateTime(2013, 12, 31)
List<DateTime> checkDates = new List<DateTime>
{ new DateTime(2011, 12, 29), new DateTime(2011, 12, 28), new DateTime(2011, 1, 30), new DateTime(2011, 2, 2) };
Giving the results
1/30/2013 12:00:00 AM
12/29/2013 12:00:00 AM
How about if you add the the nr. of years from the birthdate to today?
Something like:
(untested)
var now = DateTime.Now;
var twoDaysAgo = now.AddDays(-2);
var monthAway = now.Now.AddDays(30)
var bdays =
from p in db.Staffs
let bDay = EntityFunctions.AddYears(p.BirthDate,
EntityFunctions.DiffYears(now, p.BirthDate))
where
bDay > twoDaysAgo &&
bDay < monthAway
orderby p.BirthDate
select p;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to add the phones current time to my date time list. I need it to be able to subtract with the ticks. I have tried using phonecurrentime.ToString("dd hh:mm"); but because it's a string there are no ticks and all sorts of errors!
I need it to work with DateTime.now.
Here is my code:
InitializeComponent();
List<DateTime> theDates = new List<DateTime>();
DateTime fileDate, closestDate;
theDates.Add(new DateTime(2000, 1, 1, 10, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
// This is the date that should be found
theDates.Add(new DateTime(2000, 1, 1, 4, 22, 0));
// This is the date you want to find the closest one to
fileDate = DateTime.Now;
long min = long.MaxValue;
foreach (DateTime date in theDates)
{
if (Math.Abs(date.Ticks - fileDate.Ticks) < min)
{
min = Math.Abs(date.Ticks - fileDate.Ticks);
closestDate = date;
}
}
Darren Davies above is correct.
You can add/subtract datetime objects. The result is of type TimeSpan, which lets you easily compare date and/or time differences.
Also, you should give a name to each date you add to your list (assign to a variable then add to list). A month later you won't remember what each day meant ;)
if you have a string and want to convert it to DateTime you can use
CultureInfo cf = new CultureInfo("en-us");
if(DateTime.TryParseExact("12 12:45", "dd hh:mm", cf, DateTimeStyles.None, out fileDate))
{
// your code
}
and your code would look like:
List<DateTime> theDates = new List<DateTime>();
DateTime fileDate, closestDate;
theDates.Add(new DateTime(2000, 1, 1, 10, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
theDates.Add(new DateTime(2000, 1, 1, 3, 29, 0));
// This is the date that should be found
theDates.Add(new DateTime(2000, 1, 1, 4, 22, 0));
CultureInfo cf = new CultureInfo("en-us");
string timeToParse = phonecurrentime.ToString("dd hh:mm");
if(DateTime.TryParseExact(timeToParse, "dd hh:mm", cf, DateTimeStyles.None, out fileDate))
{
long min = long.MaxValue;
foreach (DateTime date in theDates)
{
if (Math.Abs(date.Ticks - fileDate.Ticks) < min)
{
min = Math.Abs(date.Ticks - fileDate.Ticks);
closestDate = date;
}
}
}
if you want to compare the time part of the dateTime you can use TimeOfDay property:
TimeSpan ts = DateTime.Now.TimeOfDay;
foreach (DateTime date in theDates)
{
long diff = Math.Abs(ts.Ticks - date.TimeOfDay.Ticks);
if (diff < min)
{
min = diff;
closestDate = date;
}
}
fileDate = phonecurrentime.ToString("dd hh:mm");
Will not compile. fileDate is a DateTime object. You need to assign it to another DateTime object, not a string.
If phonecurrenttime is a DateTime you can ommit the .ToString() method.
fileDate = phonecurrenttime;
Edit
From your comment, if you simply want to assign the current ddate/time to fileDate you can use DateTime.Now:
fileDate = DateTime.Now;