How do I calculate the number of days using MonthCalendar in C#? - 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);
}

Related

change persian date to gregorian date and vice versa

I used the following code in order to change Persian date to Gregorian date. for example it changes 1393/05/05 to 2014/05/26.
if (MultiView6.ActiveViewIndex == 1)
{
date = Convert.ToDateTime(txtDate.Text);
string change = date.ToString("yyyy/MM/dd");
int day1 = Convert.ToInt32(change.Substring(8, 2));
int mon1 = Convert.ToInt32(change.Substring(5, 2));
int year1 = Convert.ToInt32(change.Substring(0, 4));
PersianCalendar pc = new PersianCalendar();
change = (pc.ToDateTime(year1, mon1, day1, 0, 0, 0, 0).ToString("yyyy/MM/dd").Substring(0, 10));
date = Convert.ToDateTime(change);
}
however for some special dates such as 1393/02/29 the code stops working and I receive the above error from the first line of my code:
String was not recognized as a valid DateTime.
I suppose I would have the same problem if I want to convert 2014/05/19 to Persian date (which is 1393/02/29)....
is there a way to fix this error?
year, month and day are in PersianCalendar and you can't use them in DateTime. if you want to convert from PersianCalendar to DateTime, you have to do this:
DateTime d1=p.ToDateTime(year, month, day, 0, 0, 0, 0);
=====================================================
in your new code you have another mistake. variables day1, mon1 and year1 are in Gregorian calendar and you can't use them in PersianCalendar.ToDateTime().
All you need is to use constructor accepting Calendar - DateTime(int year, int month, int day, Calendar calendar).
string persianDateString = "1393/02/29";
string[] persianDateParts = persianDateString.Split('/');
int persianYear = int.Parse(persianDateParts[0]);
int persianMonth = int.Parse(persianDateParts[1]);
int persianDay = int.Parse(persianDateParts[2]);
PersianCalendar pc = new PersianCalendar();
DateTime date = new DateTime(persianYear, persianMonth, persianDay, pc);

How to read from string?

I'm trying to learn how to schedule pictures depending on what time a user has selected.
Here is code with questions:
private void startjob()
{
string theDate = DateTimePicker1.Value.ToString();
DateTime dt = Convert.ToDateTime(date);
{
DateTime start = new DateTime(2009, 12, 9, 10, 0, 0); //How Do I make this to read the string that is converted from DateTimePicker instead of this?
DateTime end = new DateTime(2009, 12, 10, 12, 0, 0); //How Do I make this to read the string that is converted from DateTimePicker instead of this?
DateTime now = DateTime.Now;
if ((now > start) && (now < end))
{
//match found
}
}
}
DateTimePicker.Value returns the DateTime object. You're trying to convert to and from a string type unnecessarily.
DateTime start = DateTimePickerStart.Value;
DateTime end = DateTimePickerEnd.Value;
Supposing your controls are named as DateTimePicker1 and DateTimePicker2:
private void startjob()
{
DateTime start = DateTimePicker1.Value;
DateTime end = DateTimePicker2.Value;
DateTime now = DateTime.Now;
if ((now > start) && (now < end))
{
//match found
}
}
DateTimePicker.Value property is a DateTime object itself, hence your code can be simplified, no need to convert to string.

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

How to change time in DateTime?

How can I change only the time in my DateTime variable "s"?
DateTime s = some datetime;
You can't change a DateTime value - it's immutable. However, you can change the variable to have a new value. The easiest way of doing that to change just the time is to create a TimeSpan with the relevant time, and use the DateTime.Date property:
DateTime s = ...;
TimeSpan ts = new TimeSpan(10, 30, 0);
s = s.Date + ts;
s will now be the same date, but at 10.30am.
Note that DateTime disregards daylight saving time transitions, representing "naive" Gregorian time in both directions (see Remarks section in the DateTime docs). The only exceptions are .Now and .Today: they retrieve current system time which reflects these events as they occur.
This is the kind of thing which motivated me to start the Noda Time project, which is now production-ready. Its ZonedDateTime type is made "aware" by linking it to a tz database entry.
Alright I'm diving in with my suggestion, an extension method:
public static DateTime ChangeTime(this DateTime dateTime, int hours, int minutes, int seconds, int milliseconds)
{
return new DateTime(
dateTime.Year,
dateTime.Month,
dateTime.Day,
hours,
minutes,
seconds,
milliseconds,
dateTime.Kind);
}
Then call:
DateTime myDate = DateTime.Now.ChangeTime(10,10,10,0);
It's important to note that this extension returns a new date object, so you can't do this:
DateTime myDate = DateTime.Now;
myDate.ChangeTime(10,10,10,0);
But you can do this:
DateTime myDate = DateTime.Now;
myDate = myDate.ChangeTime(10,10,10,0);
s = s.Date.AddHours(x).AddMinutes(y).AddSeconds(z);
In this way you preserve your date, while inserting a new hours, minutes and seconds part to your liking.
one liner
var date = DateTime.Now.Date.Add(new TimeSpan(4, 30, 0));
would bring back todays date with a time of 4:30:00, replace DateTime.Now with any date object
DateTime is an immutable type, so you can't change it.
However, you can create a new DateTime instance based on your previous instance. In your case, it sounds like you need the Date property, and you can then add a TimeSpan that represents the time of day.
Something like this:
var newDt = s.Date + TimeSpan.FromHours(2);
If you already have the time stored in another DateTime object you can use the Add method.
DateTime dateToUse = DateTime.Now();
DateTime timeToUse = new DateTime(2012, 2, 4, 10, 15, 30); //10:15:30 AM
DateTime dateWithRightTime = dateToUse.Date.Add(timeToUse.TimeOfDay);
The TimeOfDay property is a TimeSpan object and can be passed to the Add method. And since we use the Date property of the dateToUse variable we get just the date and add the time span.
Simplest solution :
DateTime s = //some Datetime that you want to change time for 8:36:44 ;
s = new DateTime(s.Year, s.Month, s.Day, 8, 36, 44);
And if you need a specific Date and Time Format :
s = new DateTime(s.Year, s.Month, s.Day, 8, 36, 44).ToString("yyyy-MM-dd h:mm:ss");
You can assign an initial value to a new DateTime value in many different ways:
Extension Method
Extension method DateTime
public static DateTime ChangeTime(this DateTime dateTime, int hours, int minutes, int seconds = default, int milliseconds = default)
{
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, hours, minutes, seconds, milliseconds, dateTime.Kind);
}
then using ChangeTime:
DateTime datetime = DateTime.Now; //Your DateTime
datetime = datetime.ChangeTime(12, 20, 10);
using the Add methods
DateTime datetime = DateTime.Now; //Your DateTime
datetime = datetime.Date.AddHours(12).AddMinutes(20).AddSeconds(10);
using the Timespan
DateTime datetime = DateTime.Now; //Your DateTime
datetime = datetime.Date.Add(new TimeSpan(12, 20, 10));
using initial value
DateTime datetime = DateTime.Now;
datetime = new DateTime(datetime.Year, datetime.Month, datetime.Day, 12, 20, 10);
DateTime ts = DateTime.Now;
ts = new DateTime ( ts.Year, ts.Month, ts.Day, 0, 0, 0 ) ;
Console.WriteLine ( "Today = " + ts.ToString("M/dd/yy HH:mm:ss") ) ;
Executed:
Today = 9/04/15 00:00:00
Happened upon this post as I was looking for the same functionality this could possibly do what the guy wanted. Take the original date and replace the time part
DateTime dayOpen = DateTime.Parse(processDay.ToShortDateString() + " 05:00 AM");
Adding .Date to your date sets it to midnight (00:00).
MyDate.Date
Note The equivavalent SQL is CONVERT(DATETIME, CONVERT(DATE, #MyDate))
What makes this method so good is that it's both quick to type and easy to read. A bonus is that there is no conversion from strings.
I.e. To set today's date to 23:30, use:
DateTime.Now.Date.AddHours(23).AddMinutes(30)
You can of course replace DateTime.Now or MyDate with any date of your choice.
Since DateTime is immutable, a new instance has to be created when a date component needs to be changed. Unfortunately, there is no built-in functionality to set individual components of a DateTime instance.
Using the following extension methods
public static DateTime SetPart(this DateTime dateTime, int? year, int? month, int? day, int? hour, int? minute, int? second)
{
return new DateTime(
year ?? dateTime.Year,
month ?? dateTime.Month,
day ?? dateTime.Day,
hour ?? dateTime.Hour,
minute ?? dateTime.Minute,
second ?? dateTime.Second
);
}
public static DateTime SetYear(this DateTime dateTime, int year)
{
return dateTime.SetPart(year, null, null, null, null, null);
}
public static DateTime SetMonth(this DateTime dateTime, int month)
{
return dateTime.SetPart(null, month, null, null, null, null);
}
public static DateTime SetDay(this DateTime dateTime, int day)
{
return dateTime.SetPart(null, null, day, null, null, null);
}
public static DateTime SetHour(this DateTime dateTime, int hour)
{
return dateTime.SetPart(null, null, null, hour, null, null);
}
public static DateTime SetMinute(this DateTime dateTime, int minute)
{
return dateTime.SetPart(null, null, null, null, minute, null);
}
public static DateTime SetSecond(this DateTime dateTime, int second)
{
return dateTime.SetPart(null, null, null, null, null, second);
}
you can set individual DateTime components like
var now = DateTime.Now;
now.SetSecond(0);
When you construct your DateTime object, use a constructor that allows you to specify time:
var myDateTime = new DateTime(2000, 01, 01, 13, 37, 42); // 2000-01-01 13:37:42
If you already have a DateTime object and wish to change the time, uou can add minutes, hours or seconds to your DateTime using simple methods:
var myDateTime = new DateTime(2000, 01, 01); // 2000-01-01 00:00:00
myDateTime = myDateTime.AddHours(13); // 2000-01-01 13:00:00
myDateTime = myDateTime.AddMinutes(37); // 2000-01-01 13:37:00
myDateTime = myDateTime.AddSecounds(42); // 2000-01-01 13:37:42
Notice how we have to "save" the result from each method call to the myDateTime variable. This is because the DateTime is immutable, and its methods simply create new instances with the extra hours/minutes/seconds added.
If you need to add both hours and minutes (and/or seconds) and the same time, you can simplify the code by adding a TimeSpan to the original DateTime instead:
var myDateTime = new DateTime(2000, 01, 01); // 2000-01-01 00:00:00
myDateTime += new TimeSpan(13, 37, 42); // 2000-01-01 13:37:42
If you want to set absolute hours/minues/seconds, rather than adding to the existing values, you can use the aforementioned DateTime constructor, and reuse values for year/month/day from earlier:
myDateTime = new DateTime(myDateTime.Year, myDateTime.Month, myDateTime.Day,
20, 33, 19) // 2000-01-01 20:33:19
In fact, you can't change the time once it's created.
But you can create it easily with many constructors:
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.-ctor?view=netframework-4.7.2
For example, if you want to create a DateTime changing Seconds, you can just do this:
DateTime now = DateTime.Now;
DateTime secondschanged = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, yourseconds);
If you have a DateTime like 2014/02/05 18:19:51 and want just 2014/02/05, you can do that:
_yourDateTime = new DateTime(_yourDateTime.Year, _yourDateTime.Month, _yourDateTime.Day)
Use Date.Add and add a New TimeSpan with the new time you want to add
DateTime dt = DateTime.Now
dt.Date.Add(new TimeSpan(12,15,00))
int year = 2012;
int month = 12;
int day = 24;
int hour = 0;
int min = 0;
int second = 23;
DateTime dt = new DateTime(year, month, day, hour, min, second);
To set end of a day:
date = new DateTime(date.Year, date.Month, date.Day, 23, 59, 59);
Here is a method you could use to do it for you, use it like this
DateTime newDataTime = ChangeDateTimePart(oldDateTime, DateTimePart.Seconds, 0);
Here is the method, there is probably a better way, but I just whipped this up:
public enum DateTimePart { Years, Months, Days, Hours, Minutes, Seconds };
public DateTime ChangeDateTimePart(DateTime dt, DateTimePart part, int newValue)
{
return new DateTime(
part == DateTimePart.Years ? newValue : dt.Year,
part == DateTimePart.Months ? newValue : dt.Month,
part == DateTimePart.Days ? newValue : dt.Day,
part == DateTimePart.Hours ? newValue : dt.Hour,
part == DateTimePart.Minutes ? newValue : dt.Minute,
part == DateTimePart.Seconds ? newValue : dt.Second
);
}
I have just come across this post because I had a similar issue whereby I wanted to set the time for an Entity Framework object in MVC that gets the date from a view (datepicker) so the time component is 00:00:00 but I need it to be the current time. Based on the answers in this post I came up with:
myEntity.FromDate += DateTime.Now.TimeOfDay;
//The fastest way to copy time
DateTime justDate = new DateTime(2011, 1, 1); // 1/1/2011 12:00:00AM the date you will be adding time to, time ticks = 0
DateTime timeSource = new DateTime(1999, 2, 4, 10, 15, 30); // 2/4/1999 10:15:30AM - time tick = x
justDate = new DateTime(justDate.Date.Ticks + timeSource.TimeOfDay.Ticks);
Console.WriteLine(justDate); // 1/1/2011 10:15:30AM
Console.Read();
DateTime s;
//s = datevalue
s = s.AddMilliseconds(10);
s = s.AddMinutes(10);
s = s.AddSeconds(10);
s = s.AddHours(10);
you could add +ve/-ve values in parameter.
s.Add(new TimeSpan(1, 1, 1));
Doesn't that fix your problems??
Dateime dt = DateTime.Now;
dt = dt.AddSeconds(10);
I prefer this:
DateTime s = //get some datetime;
s = new DateTime(s.Year, s.Month,s.Day,s.Hour,s.Minute,0);
Using an extencion to DateTime:
public enum eTimeFragment
{
hours,
minutes,
seconds,
milliseconds
}
public static DateTime ClearTimeFrom(this DateTime dateToClear, eTimeFragment etf)
{
DateTime dtRet = dateToClear;
switch (etf)
{
case eTimeFragment.hours:
dtRet = dateToClear.Date;
break;
case eTimeFragment.minutes:
dtRet = dateToClear.AddMinutes(dateToClear.Minute * -1);
dtRet = dtRet.ClearTimeFrom(eTimeFragment.seconds);
break;
case eTimeFragment.seconds:
dtRet = dateToClear.AddSeconds(dateToClear.Second * -1);
dtRet = dtRet.ClearTimeFrom(eTimeFragment.milliseconds);
break;
case eTimeFragment.milliseconds:
dtRet = dateToClear.AddMilliseconds(dateToClear.Millisecond * -1);
break;
}
return dtRet;
}
Use like this:
Console.WriteLine (DateTime.Now.ClearTimeFrom(eTimeFragment.hours))
this has to return:
2016-06-06 00:00:00.000
What's wrong with DateTime.AddSeconds method where you can add or substract seconds?
Try this one
var NewDate = Convert.ToDateTime(DateTime.Now.ToString("dd/MMM/yyyy")+" "+"10:15 PM")/*Add your time here*/;
The best solution is:
currdate.AddMilliseconds(currdate.Millisecond * -1).AddSeconds(currdate.Second * -1).AddMinutes(currdate.Minute * -1).AddHours(currdate.Hour * -1);
here is a ghetto way, but it works :)
DateTime dt = DateTime.Now; //get a DateTime variable for the example
string newSecondsValue = "00";
dt = Convert.ToDateTime(dt.ToString("MM/dd/yyyy hh:mm:" + newSecondsValue));

Categories