DateTime manipulation - c#

Here is my code:
DateTime startDate = Convert.ToDateTime( orderDate ).AddMonths(-1);
DateTime endDate = Convert.ToDateTime( orderDate );
orderDate is a valid date I pass in.
How do I always guarantee startDate is the first day of the previous month for orderDate?
How do I always guarantee endDate is the last day of the month for orderDate?
Example:
orderDate = 5/4/2012
I want startDate to be 4/1/2012 (or 04/1/2012 whichever is default)
I want endDate to be 4/30/2012
How can I acheive this?

DateTime startDate = Convert.ToDateTime( orderDate ).AddMonths(-1);
// set to first of month
startDate = startDate.AddDays(1-startDate.Day);
// Set end date to last of month, which is one day before first of next month
DateTime endDate = startDate.AddMonths(1).AddDays(-1);

origDate = startDate.AddMonths(-1);
DateTime myDate = new DateTime(origDate.Year, origDate.Month, 1);
http://msdn.microsoft.com/en-us/library/xcfzdy4x.aspx
Something like this... We do it often enough that we've just created an extension method on date.

DateTime startDate = new DateTime( orderDate.Month == 1 ? orderDate.Year - 1 : orderDate.Year, orderDate.Month - 1, 1);
DateTime endDate = new DateTime(orderDate.Year, orderDate.Month, DateTime.DaysInMonth(orderDate.Year, OrderDate.Month));

Use DateTime constructor that takes separate values for each year, month, day,... and adjust them accodringly (i.e. first of the month means day = 1).

var orderDate = DateTime.Now.Date;
var endDate = orderDate.AddDays(-orderDate.Day);
var startDate = endDate.AddDays(-(endDate.Day - 1));

Related

Match all rows on particular day using LINQ to SQL

How would you find all rows in a table that have a time matching a particular day?
The SQL DataType for the column Time is datetime.
For example, let's say you want all rows from 9/20/2014 and the table column Time looks like this...2014-09-20 17:02:05.903
var query = from t in SomeTable
where t.Time // don't know what goes here
select t;
You could try something like this one:
// Define your startDate. In our case it would be 9/20/2014 00:00:00
DateTime startDate = new DateTime(2014,09,20);
// Define your endDate. In our case it would be 9/21/2014 00:00:00
DateTime endDate = startDate.AddDays(1);
// Get all the rows of SomeTable, whose Time is between startDate and endDate.
var query = from t in SomeTable
where t.Time>= startDate and t.Time<=endDate
select t;
void DoSomethingWithSomeTable(int day, int month, int year)
{
var query = from t in SomeTable
where t.Time.Date.Equals(new DateTime(year, month, day))
select t;
}
var query = from t in SomeTable
where t.Time.Date == new DateTime(2014, 9, 20)
select t;
You could use extension methods to make it a little more readable:
public static class DateTimeExtensions
{
public static bool InRange(this DateTime dateToCheck, DateTime startDate, DateTime endDate)
{
return dateToCheck >= startDate && dateToCheck < endDate;
}
}
Now you can write:
dateToCheck.InRange(startDate, endDate)
or
var start = new DateTime(2014, 9, 20);
dateToCheck.InRange(start, start.AddDays(1));
(this solution was found posted here)

Code to calculate no.of days between two dates

C# Code to calculate no.of days between two dates...I have start date in one textbox and end date in another textbox and i need to get no. of days between the two dates and to be displayed in third textbox and it should exclude holidays and weekends(saturday and sunday).
You can parse the textbox dates to date time object and then try something on the following lines.
DateTime startDate = new DateTime(2013, 03, 01);
DateTime endDate = DateTime.Today; // 12 March 2013
int totalDays = 0;
while (startDate <= endDate)
{
if (startDate.DayOfWeek == DayOfWeek.Saturday
|| startDate.DayOfWeek == DayOfWeek.Sunday)
{
startDate = startDate.AddDays(1);
continue;
}
startDate = startDate.AddDays(1);
totalDays++;
}
Console.WriteLine("Total days excluding weekends: {0}", totalDays);
var dateDiff = FirstDate - SecondDate;
double totalDays = dateDiff.TotalDays;
if you have two dates in textboxes viz textBox1 and textBox2
DateTime date1= new DateTime();
DateTime date2 = new DateTime();
double days;
bool isDate1Valid =DateTime.TryParse(textBox1.Text, out date1);
bool isDate2Valid =DateTime.TryParse(textBox2.Text, out date2);
if(isDate1Valid && isDate2Valid)
days = (date1-date2).TotalDays;
Edit
If you need to do it without looping, Here is how to do it..
If date difference is too large, looping may consume some amount of extra time.
Try this..
DateTime startdate = DateTime.Parse("somedate");
DateTime enddate = DateTime.Parse("somedate");
int daycount = 0;
while (startdate < enddate)
{
startdate = startdate.AddDays(1); // Fixed
int DayNumInWeek = (int)startdate.DayOfWeek;
if (DayNumInWeek != 0)
{
if (DayNumInWeek != 6)
{ daycount += 1; }
}
}

c# DateTime, Timespan question about period of times

What I'm basically looking to do is monitor a period of time between 2 dates,
say 01/01/2011 to 04/04/2011.
I am then looking for a way to then compare 2 new dates, where if these new dates fall
between the above ones i can say assign a boolean a value and if they dont i wont.
so if 02/02/2011 to 03/03/2011 then assign the boolean wheras if outside then no.
??
You can just use normal compare operators with DateTime to do this.
For example
public bool Check(DateTime d1, DateTime d2)
{
DateTime StartDate = new DateTime(2011,1,1);
DateTime EndDate = new DateTime(2011,4,4);
return ((d1 >= StartDate && d1 <= EndDate) && (d2 >= StartDate && d2 <= EndDate));
}
This is a straight-forward as:
bool isInside = (testDate >= startDate && testDate <= endDate);
This example show how to check if a date is between two dates.
Code has been tested and works:
DateTime dtStart = new DateTime(2011, 02, 02);
DateTime dtEnd = new DateTime(2011, 03, 03);
if (DateTime.Now >= dtStart && DateTime.Now <= dtEnd)
{
// Date is within range
}

Get the number of days between two different DateTime objects

How can I get the difference of days between two DateTime objects?
private static string DaysAfterAYear(DateTime initialDate)
{
DateTime endDate = initialDate.AddYears(1);
endDate = endDate.AddMonths(1);
return ??
}
I need to get the difference between initialDate and endDate.
Use the subtract method:
static void Main(string[] args)
{
DateTime begin = DateTime.Now;
DateTime end = begin.AddYears(1).AddMonths(1);
var result = end.Subtract(begin).TotalDays;
}
DateTime dt1 = new DateTime(2011,01,01);
DateTime dt2 = new DateTime(2011,01,20);
int ireturn = (int)dt2.Subtract(dt1).TotalDays;
Subtracting DateTimes will yield a TimeSpan:
var elapsedDays = (endDate - initialDate).TotalDays;
DateTime start = DateTime.Now;
DateTime end = DateTime.Now.AddDays(5);
TimeSpan span = end.Subtract(start);
return span.Days;
int days = 10;
DateTime initialDate = DateTime.Now;
DateTime endDate = DateTime.Now.AddDays(days);
TimeSpan duration = endDate.Subtract(initialDate);
In this example you can use either span.Days or span.TotalDays, however you have to be very careful with TimeSpan properties. If you look at the TotalHours vs Hours for example you'll see that they are not the same.
The Hours property is the number of hours remaining after the days property has been taken off (in this case zero), the Total hours is the TimeSpan represented in hours.

Exact time between 2 DateTime?

I would like to know many minutes between 2 dates?
Example : Now - tommorow at the exact time would return me 1440.
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(1);
int diff = dt2.Subtract(dt1).TotalMinutes;
Look at the TimeSpan class.
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(1);
TimeSpan diff = date2.Subtract(date1);
Console.WriteLine(diff.Minutes);
DateTime currentTime = DateTime.Now;
DateTime tommorowTime = currentTime.AddDays(1);
TimeSpan diffTime = tommorowTime - currentTime ;
Console.WriteLine(diffTime.TotalMinutes);

Categories

Resources