Setting a DateTime to the first of the next month? - c#

If I have var olddate = DateTime.Parse('05/13/2012');
and I want to get var newdate = (the first of the month after olddate, 06/01/2012 in this case);
What would I code? I tried to set the month+1 but month has no setter.

Try this:
olddate = olddate.AddMonths(1);
DateTime newDate = new DateTime(olddate.Year, olddate.Month, 1,
0, 0, 0, olddate.Kind);

This won't ever cause out-of-range errors, and will preserve the DateTime's Kind.
dt = dt.AddMonths(1.0);
dt = new DateTime(dt.Year, dt.Month, 1, 0, 0, 0, dt.Kind);

You have to define the Month and Year rightly, and after set the 1ยช day. Try this:
// define the right month and year of next month.
var tempDate = oldDate.AddMonths(1);
// define the newDate with the nextmonth and set the day as the first day :)
var newDate = new DateTime(tempDate.Year, tempDate.Month, 1); //create

Try this simple one-liner:
var olddate = DateTime.Parse("05/13/2012");
var newdate = olddate.AddDays(-olddate.Day + 1).AddMonths(1);
// newdate == DateTime.Parse("06/01/2012")

lots of examples...pick your posion ;)
var olddate = DateTime.Parse("05/12/2012");
int currentDay = ((DateTime)olddate).Day;
//can always replace the while loop and just put a 1 for current day
while(currentDay != 1)
currentDay--;
var newdate = (DateTime.Parse(olddate.AddMonths(1).Month.ToString() + "/" + currentDay.ToString() + "/" + olddate.AddMonths(1).Year.ToString()));

Related

Get time left until sunday 9:30 pm

What I want to do is basically in the question title.
This is what I've tried so far, unsuccessfully.
Note that I haven't implemented exact hour and minute yet (9:30 pm).
It actually seems to always return a value between 00:00:59 and 00:00:01 for some reason
DateTime nextSunday = DateTime.Today.AddDays(((int)DayOfWeek.Sunday - (int)DateTime.Today.DayOfWeek + 7) % 7) + new TimeSpan(21, 30, 0);
TimeSpan untilNextSunday = nextSunday - DateTime.Now;
await ReplyAsync($"It is in **{TimeSpan.FromSeconds(untilNextSunday.Seconds)}**");
Which equals to
var today = DateTime.Today;
var daysUntilSunday = ((int)DayOfWeek.Sunday - (int)today.DayOfWeek + 7) % 7;
var nextSunday = today.AddDays(daysUntilSunday);
var ts = new TimeSpan(21, 30, 0);
nextSunday = nextSunday.Date + ts;
TimeSpan untilNextSunday = nextSunday - DateTime.Now;
If possible, I'd also like to use Paris TimeZone.
I tend to find all of the DateTime.Today.AddDays(((int)DayOfWeek.Sunday - (int)DateTime.Today.DayOfWeek + 7) % 7) + new TimeSpan(21, 30, 0) arithmetic quite confusing. Instead I try to go with a more iterative approach that can be clearly reasoned about.
Try this:
public static DateTime GetNextDateTime(DateTime now, DayOfWeek targetDay, TimeSpan targetTime)
{
DateTime target = now.Date.Add(targetTime);
while (target < now || target.DayOfWeek != targetDay)
{
target = target.AddDays(1.0);
}
return target;
}
Now you can use it like this:
DateTime now = DateTime.Now;
DateTime target = GetNextDateTime(DateTime.Now, DayOfWeek.Sunday, new TimeSpan(21, 30, 0));
TimeSpan untilNextSunday = target.Subtract(now);
Here's an example using Noda Time, including time zone handling. It doesn't attempt to handle "interesting" situations where (say) you ask for the next 1:30am, and it's already 1:45am but the clock goes back at 2am - in which case the right answer is really "45 minutes" but this code will give you a week instead.
using System;
using NodaTime;
class Test
{
static void Main()
{
var duration = GetDurationToNext(
IsoDayOfWeek.Sunday, new LocalTime(21, 30),
DateTimeZoneProviders.Tzdb["Europe/Paris"],
SystemClock.Instance);
Console.WriteLine($"Duration: {duration}");
}
static Duration GetDurationToNext(
IsoDayOfWeek dayOfWeek,
LocalTime timeOfDay,
DateTimeZone zone,
IClock clock) // Or just take an instant
{
var now = clock.GetCurrentInstant();
var localNow = now.InZone(zone).LocalDateTime;
var localNext = localNow
.Date.With(DateAdjusters.NextOrSame(dayOfWeek))
.At(timeOfDay);
// Handle "we're already on the right day-of-week, but
// later in the day"
if (localNext <= localNow)
{
localNext = localNext.PlusWeeks(1);
}
var zonedNext = localNext.InZoneLeniently(zone);
var instantNext = zonedNext.ToInstant();
return instantNext - now;
}
}

How do I calculate the number of days using MonthCalendar in C#?

I have added the calendar form and it won't let me select 2 dates. It assigns every click to the start date so when I try this it always tells me the difference is 1 and the start date is always changed to whatever my next click is?
Is it possible to have it default to today's date for the start date and then have every other click determine the end date? When I tried to assign today's date within the datechanged event handler it wouldn't let me change the month because it kept focusing on the startdate?
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
numDays = Convert.ToInt32((monthCalendar1.SelectionEnd - monthCalendar1.SelectionStart).TotalDays);
MessageBox.Show("num " + numDays);
}
// Sets the Month Calenders Min & Max to days in current month.
DateTime dt = DateTime.Today;
DateTime firstDay = new DateTime(dt.Year, dt.Month, 1, 0, 0, 0);
DateTime lastDay = new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));
dateMonthCalender.MinDate = firstDay;
dateMonthCalender.MaxDate = lastDay;
The above will set min and max to days in current month
If you want to set the min to today
dateMonthCalender.MinDate = DateTime.Now;
Hope that helps..
Okay so declare two ints and assign one to selected day and the other to today and create yourself a method
int selectedDay;
int todayValue;
DateTime firstDay = new DateTime(dt.Year, dt.Month, 1, 0, 0, 0);
DateTime today = DateTime.Today;
string todayShort = today.ToShortDateString();
string thisDay = todayShort.Substring(0, 2);
todayValue = Convert.ToInt32(thisDay);
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
// Shorten date format to day and assign it.
string dMC = dateMonthCalender.SelectionRange.Start.ToShortDateString();
string takeDMCDay = dMC.Substring(0, 2);
selectedDay = Convert.ToInt32(takeDay);
}

Need Function to Get First day and last day of current week

I have two labels First day and Last day in which I want to update it on button click.
I need Function to Get First day and last day of current date so that I can display it on click of next and previous button.
Here is what I have so far:
CultureInfo cultureInfo = CultureInfo.CurrentCulture;
DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek;
firstDayInWeek = dayInWeek.Date;
lastDayInWeek = dayInWeek.Date;
while (firstDayInWeek.DayOfWeek != firstDay)
firstDayInWeek = firstDayInWeek.AddDays(-1);
but does not give me the next week after this month.
This is what exactly i'm looking for :
Any one can help to make this working using a single function.
DateTime baseDate = DateTime.Now;
var thisWeekStart = baseDate.AddDays(-(int)baseDate.DayOfWeek);
var thisWeekEnd = thisWeekStart.AddDays(7).AddSeconds(-1);
Try this :
private static void GetWeek(DateTime now, CultureInfo cultureInfo, out DateTime begining, out DateTime end)
{
if (now == null)
throw new ArgumentNullException("now");
if (cultureInfo == null)
throw new ArgumentNullException("cultureInfo");
var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
int offset = firstDayOfWeek - now.DayOfWeek;
if (offset != 1)
{
DateTime weekStart = now.AddDays(offset);
DateTime endOfWeek = weekStart.AddDays(6);
begining = weekStart;
end = endOfWeek;
}
else
{
begining = now.AddDays(-6);
end = now;
}
}
Usage example:
DateTime begining;
DateTime end;
var testDate = new DateTime(2012, 10, 10);
GetWeek(testDate, new CultureInfo("fr-FR"), out begining, out end);
Console.WriteLine("Week {0} - {1}",
begining.ToShortDateString(),
end.ToShortDateString()); // will output Week 10/8/2012 - 10/14/2012
So, on a button click, you have a one week period. Lets say that is defined by a starting date. The DateTime structure has a property DayOfWeek that returns an enum like DayOfWeek.Sunday. So here is a code fragment that may help:
var startOfWeek = DateTime(xx, yy ...); // defined by your business code
var firstDayOfWeek = startOfWeek.DayOfWeek;
var lastDayOfWeek = firstDayOfWeek.AddDays(6).DayOfWeek;
I have not compiled this code, straight off my head, so hope it is okay.

Set Textbox value to last month

How do i set the textbox value to last day of last month(to end of previous month), using today's date.
for example:
if today is 23/03/2012 textbox value should be 29/02/2012
if come next month and date is 12/04/2012 then textbox value should be 31/03/2012 and so on
Thanks
Take the first day of the current month and subtract 1:
DateTime value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1);
DateTime date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1);
textBox1.Text = date.ToShortDateString();
Use DateTime.DaysInMonth to accomplish this:
var daysInMonth = DateTime.DaysInMonth(dt.Year, dt.Month - 1);
var lastDayInMonth = new DateTime(dt.Year, dt.Month - 1, daysInMonth);
textBox1.Text = lastDayInMonth.ToString("dd/MM/yyyy");
In C#:
DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddDays(-1);
Then call .ToString() and pass in whatever format you like.
Get the first day of the month and subtract one day.
DateTime lastDayOfThePreviousMonth = dateSelected.AddDays(-dateSelected.Day);

Add hours or minutes to the current time

I want to increase time to current time.
For example, I have the time of the problem and the expected time to complete them. How can I add to it?
(DateTime.Now.ToShortDateString() + ...)
You can use other variables:
DateTime otherDate = DateTime.Now.AddMinutes(25);
DateTime tomorrow = DateTime.Now.AddHours(25);
You can use the operators +, -, +=, and -= on a DateTime with a TimeSpan argument.
DateTime myDateTime = DateTime.Parse("24 May 2009 02:19:00");
myDateTime = myDateTime + new TimeSpan(1, 1, 1);
myDateTime = myDateTime - new TimeSpan(1, 1, 1);
myDateTime += new TimeSpan(1, 1, 1);
myDateTime -= new TimeSpan(1, 1, 1);
Furthermore, you can use a set of "Add" methods
myDateTime = myDateTime.AddYears(1);
myDateTime = myDateTime.AddMonths(1);
myDateTime = myDateTime.AddDays(1);
myDateTime = myDateTime.AddHours(1);
myDateTime = myDateTime.AddMinutes(1);
myDateTime = myDateTime.AddSeconds(1);
myDateTime = myDateTime.AddMilliseconds(1);
myDateTime = myDateTime.AddTicks(1);
myDateTime = myDateTime.Add(new TimeSpan(1, 1, 1));
For a nice overview of even more DateTime manipulations see THIS
You can also add a TimeSpan to a DateTime, as in:
date + TimeSpan.FromHours(8);
Please note that you may add - (minus) sign to find minutes backwards
DateTime begin = new DateTime();
begin = DateTime.ParseExact("21:00:00", "H:m:s", null);
if (DateTime.Now < begin.AddMinutes(-15))
{
//if time is before 19:45:00 show message etc...
}
and time forward
DateTime end = new DateTime();
end = DateTime.ParseExact("22:00:00", "H:m:s", null);
if (DateTime.Now > end.AddMinutes(15))
{
//if time is greater than 22:15:00 do whatever you want
}

Categories