how could i programmatically detect, how many days are there for a particular month & year.
It's already there:
DateTime.DaysInMonth(int year, int month);
should do it.
Something like this should do what you want:
static int GetDaysInMonth(int year, int month) {
DateTime dt1 = new DateTime(year, month, 1);
DateTime dt2 = dt1.AddMonths(1);
TimeSpan ts = dt2 - dt1;
return (int)ts.TotalDays;
}
You get the first day of the month, add one month and count the days in between.
Related
I am trying to create a DateTime object, but it seems to be giving me an error.
int month = "1"
int year = "2017"
DateTime date = new DateTime(year, month, DateTime.Day);
It doesn't seem to like DateTime.Day. It says an object reference is required for the non-static field.
How could I get today's day(16th) as a parameter? Also, I need the date to have hh:mm:sss... how could I do that?
Thanks for your help!
Use
var day = DateTime.Now.Day;
for today.
You can add hh:mm:sss to the date object in the constructor too:
DateTime date = new DateTime(year, month, DateTime.Now.Day, 10, 11, 12);
10 => hours
11 => minutes
12 => seconds
Of course you can use DateTime.Now.Hour etc. for the current values.
An ArgumentOutOfRangeException is thrown if the values are not valid for a real date, e.g. 30.2.xxxx.
You can print the date object in different formats, read the MS Documentation for all possibilities.
It should be:
int month = 1;
int year = 2017;
DateTime date = new DateTime(year, month, DateTime.Now.Day);
Take note, you declare integer without quotation marks:
int month = 1;
To convert it on 24 hour format with milliseconds as requested on comment:
string strResult = string.Format("{0:MM/dd/yyyy HH:mm:ss.fff}", date);
//Results: 02/17/2017 00:00:00.000
For 12 hour:
string strResult = string.Format("{0:MM/dd/yyyy hh:mm:ss.fff}", date);
//Results: 02/17/2017 12:00:00.000
In my form I have three separate dropdown lists for birthday: Day, Month, and Year.
In my database, I have a column "birthday" with type date.
How will I convert those values from the dropdownlists in a specific date format to be accepted in the database?
Dropdown list values:
Day Month Year
1 Jan 1990
2 Feb 1991
3 Mar 1992
...and so on.
I tried this. It works but I know there's a better way:
DateTime bday = DateTime.Parse(String.Format("{0}/{1}/{2}", dropDay.SelectedValue, dropMonth.SelectedValue, dropYear.SelectedValue));
You should use DateTime and initilize it like this:
DateTime birthday = new DateTime(int year, int month, int day);
First you have to parse your Month string to int and than you should use DateTime and initialize it like this (as AitorFDK wrote) :
int month = DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month
DateTime birthday = new DateTime(int year, int month, int day);
When my application starts I have a datetimepicker for a start time and end time.
dvSubmittedDateBegin.Format = DateTimePickerFormat.Custom;
dvSubmittedDateBegin.CustomFormat = "MMM dd yyyy - hh mm tt";
Everything works. However I've been asked to have the start default default at 5AM.
I created a new datetime and assigned the dvSubmittedDateBegin.Value - dt;
However the new datetime I guess I have to specify every int?
DateTime dt = new DateTime(2015, 6, 24, 05, 00, 0);
What happens tomorrow when its 6/25? Not sure how to fix this.
How about like;
DateTime dt = DateTime.Today + TimeSpan.FromHours(5);
or more simple
DateTime dt = DateTime.Today.AddHours(5);
You will get the current date from midnight with DateTime.Today and you will add 5 hours to it and it will be 5 AM of the current day.
You can use the AddDays(), AddHours(), AddMinutes() etc. methods:
DateTime dt = DateTime.Today.AddHours(5);
You can create a function that would return a particular date where you pass all the components and define time components as default parameters:
DateTime CreateDateWith5amStart(int year, int month, int day, int hour = 5, int minute = 0, int second = 0)
{
return new DateTime(year, month, day, hour, minute, second)
}
If they provide only date components, it will set time to 5 a.m. If they need a different time, they can provide time components.
I have a calendar that's first week day starts in Sunday and ends in Saturday.
Right now I can only disable days in the calendar current month because I don't know the first and last day in the calendar.
The code that Im using is pretty simple right now:
private List<DateTime> GetDisabledDates(DateTime fromDate, DateTime toDate){
// right now fromDate and toDate are the start and end days in a month
var disabledDates = SearchDates(fromDate, toDate);
return disabledDates;
}
So, what I need is to get the first day and last day showed in the calendar month, considering that week starts in Sunday and ends in Saturday.
Any clue on how to dinamically get first and last (yellow marked dates) from a specific month? Considering the calendar configuration?
Well for the first day in this view something like this should do it
//Using UTC to counter daylight saving problems
var month = new DateTime(2014, 8, 1, 0, 0, 0, DateTimeKind.Utc);
var firstInView = month.Subtract(TimeSpan.FromDays((int) month.DayOfWeek));
For the remaining days you just need to calculate the amount left in (7 * NumRows) - (DaysOfCurrentMonth + DaysOfPreviousMonth), where DaysOfPreviousMonth is the DayOfWeek property of this month first day again.
The solution that works for me:
int totalCalendarDays = 42; // matrix 7 x 6
// set the first month day
DateTime firstDayMonth = new DateTime(date.Year, date.Month, 1);
// set the lastmonth day
DateTime lastDayMonth = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
// now get the first day week of the first day month (0-6 Sun-Sat)
byte firstDayWeek = (byte) firstDayMonth.DayOfWeek;
// now get the first day week of the last day month (0-6 Sun-Sat)
byte lastDayWeek = (byte) lastDayMonth.DayOfWeek;
// now the first day show in calendar is the first day month minus the days to 0 (sunday)
DateTime firstDayCalendar = firstDayMonth.Subtract(TimeSpan.FromDays(firstDayWeek));
int tempDays = (lastDayMonth - firstDayCalendar).Days;
DateTime lastDayCalendar = lastDayMonth.Add(TimeSpan.FromDays(totalCalendarDays - tempDays - 1));
Maybe is a better way to do this :)
HereĀ“s my suggestion, defining year and month as parameters:
public DateTime[] GetMonthDisplayLimits(int year, int month)
{
int lastDay = DateTime.DaysInMonth(year, month);
var firstDayInMonth = new DateTime(year, month, 1);
var lastDayInMonth = new DateTime(year, month, lastDay);
var firstDayInView = firstDayInMonth.AddDays(-1 * (int) firstDayInMonth.DayOfWeek);
var lastDayInView = lastDayInMonth.AddDays((int) (6 - lastDayInMonth.DayOfWeek));
return new DateTime[] { firstDayInView, lastDayInView };
}
DateTime[] monthDisplayLimits = GetMonthDisplayLimits(2014, 8);
var firstDayInView = monthDisplayLimits[0];
var lastDayInView = monthDisplayLimits[1];
Since "DayOfWeek" is a value between 0 and 6, this approach rounds down the first weekday and rounds up the last weekday.
How can I get the month according to a specified week number? For example, if a get the week number 2 return the month 1 (January)?
Take the week number and multiply it by 7. For example, if it is week number 12, multiply 12 by 7. This will indicate the number of days it has been, rounded to the nearest week.
Divide this number by 30. In the example, the number we derived from the calculation was 84. 84 divided by 30 is 2.8
Use this number to figure out the month. 2.8 means that it is March. The number before the decimal point indicates the months past. Always round the number up, this will give you the current month.
Read more: http://www.ehow.com/how_7444970_calculate-month-week-number.html#ixzz2zYJVK4S8
Well, first we should come to terms; since week can start in one month and ends in second month, let's find out in which month the given week starts and ends in separate methods.
Let's implement WeekStart: given a date we want to find out the corresponding week start date:
private static DateTime WeekStart(DateTime date, DayOfWeek firstDayOfWeek) {
DayOfWeek current = date.DayOfWeek;
return (current >= firstDayOfWeek)
? date.Date.AddDays(firstDayOfWeek - current)
: date.Date.AddDays(-7 + (int)firstDayOfWeek - (int)current);
}
Then we can try to guess the right week; then we have to correct it (take previous or next week when required):
private static DateTime NthWeekStart(
int year, int week, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) {
DateTime guess = new DateTime(year, 1, 1).AddDays((week - 1) * 7);
// Or CurrentCulture
int actual = CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(
guess, rule, firstDayOfWeek);
return WeekStart(guess.AddDays((week - actual) * 7), firstDayOfWeek);
}
Finally, we can get corresponding months:
private static int WeekStartMonth(
int year, int week, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) {
return NthWeekStart(year, week, rule, firstDayOfWeek).Month;
}
private static int WeekEndMonth(
int year, int week, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) {
return NthWeekStart(year, week, rule, firstDayOfWeek).AddDays(6).Month;
}
Demo:
int year = 2020;
int week = 36;
CalendarWeekRule rule = CalendarWeekRule.FirstDay;
DayOfWeek day = DayOfWeek.Sunday;
int monthStart = WeekStartMonth(year, week, rule, day);
int monthEnd = WeekEndMonth(year, week, rule, day);
Console.Write($"{week}th week of {year} starts in month #{monthStart} ends in month #{monthEnd}");
Outcome:
36th week of 2020 starts in month #8 ends in month #9