Exact time between 2 DateTime? - c#

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

Related

Get all the dates of current week

Say I consider Sunday - Saturday as a week, how do I get all the dates of the current week in c#?
For example, current date is 30th March 2017, the output I need is,
26-March-2017,
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017
You can try DateTimeFormat to find out current week's starting date and Linq to generate the string:
DateTime startOfWeek = DateTime.Today.AddDays(
(int) CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek -
(int) DateTime.Today.DayOfWeek);
string result = string.Join("," + Environment.NewLine, Enumerable
.Range(0, 7)
.Select(i => startOfWeek
.AddDays(i)
.ToString("dd-MMMM-yyyy")));
In case of en-US culture you'll get (week starts from Sunday)
26-March-2017, // <- starts from Sunday
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017
In case of, say, ru-RU culture you'll get (week starts from Monday)
27-марта-2017, // <- Starts from Monday
28-марта-2017,
29-марта-2017,
30-марта-2017,
31-марта-2017,
01-апреля-2017,
02-апреля-2017
Assuming that Sunday will be the start day of the week, as it is mentioned in the question I suggest following solution.
var today = DateTime.Now.Date; // This can be any date.
Console.WriteLine(today.DayOfWeek);
var day = (int)today.DayOfWeek; //Number of the day in week. (0 - Sunday, 1 - Monday... and so On)
Console.WriteLine(day);
const int totalDaysOfWeek = 7; // Number of days in a week stays constant.
for (var i = -day; i < -day + totalDaysOfWeek; i++)
{
Console.WriteLine(today.AddDays(i).Date);
}
I found this here
DayOfWeek Day = DateTime.Now.DayOfWeek;
int Days = Day - DayOfWeek.Monday; //here you can set your Week Start Day
DateTime WeekStartDate = DateTime.Now.AddDays(-Days);
DateTime WeekEndDate1 = WeekStartDate.AddDays(1);
DateTime WeekEndDate2 = WeekStartDate.AddDays(2);
DateTime WeekEndDate3 = WeekStartDate.AddDays(3);
DateTime WeekEndDate4 = WeekStartDate.AddDays(4);
DateTime WeekEndDate5 = WeekStartDate.AddDays(5);
DateTime WeekEndDate6 = WeekStartDate.AddDays(6);
In my opinion, an extension method is the most useful approach:
public static IEnumerable<DateTime> GetDatesOfWeek(this DateTime date, CultureInfo ci) {
Int32 firstDayOfWeek = (Int32) ci.DateTimeFormat.FirstDayOfWeek;
Int32 dayOfWeek = (Int32) date.DayOfWeek;
DateTime startOfWeek = date.AddDays(firstDayOfWeek - dayOfWeek);
var valuesDaysOfWeek = Enum.GetValues(typeof(DayOfWeek)).Cast<Int32>();
return valuesDaysOfWeek.Select(v => startOfWeek.AddDays(v));
}
Use as follows:
DateTime myDate = DateTime.Today;
IEnumerable<DateTime> result = myDate.GetDatesOfWeek(CultureInfo.CurrentCulture);
foreach ( DateTime d in result ) {
Console.WriteLine(d);
}

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

How do I compute a date a specified period in the future?

I have this:
string dataNow = DateTime.Today.tostring();
string dateAfter = dateNow + ( 20 days);
How do I find the date in 20 days?
How do I find the number of days in the month?
Your likely intent is to work with a date as a date type DateTime. In which case, don't call ToString() before you've completed manipulating the date:
string dataNow = DateTime.Today.AddDays(20).ToString();
DateTime.AddDays
After update:
To get the number of days in the current month:
var date = DateTime.Today;
int days = DateTime.DaysInMonth(date.Year, date.Month);
DateTime.DaysInMonth
This should do it:
DateTime dtNow = DateTime.Today;
string dateNow = dtNow.ToString();
string dateAfter = dtNow.AddDays(20).ToString();
int DaysInTheMonth = DateTime.DaysInMonth(dtNow.Year, dtNow.Month);
DateTime today = DateTime.Today;
DateTime later = today.AddDays(20);
string todayAsString = today.ToString("d");
string laterAsString = later.ToString("d");
int daysThisMonth = DateTime.DaysInMonth(today.Year, today.Month);
int daysLaterMonth = DateTime.DaysInMonth(later.Year, later.Month);

DateTime manipulation

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

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.

Categories

Resources