How can I determine the last day of the month [duplicate] - c#

This question already has answers here:
Last day of the month in .NET
(5 answers)
Closed 7 years ago.
How can I determine the last day of the month, for the tested month, when the user enters a date into textbox that is further from the available last day for that month? Also how do I feed that back to the user.
When the user enters the date, for example, of April 31, 2015, the date should automatically change to April 30, 2015.
I would like to try doing this using c#

3rd EDIT: The below will get you close to what you're asking for but really just make use of a datepicker control it will help prevent the majority of invalid dates and save you a good amount of development time
2nd EDIT: So TryParse is beneficial because if the date is valid, continue and your done. If you have an invalid date, which TryParse will tell you, then you can compare the value that was input for the day value and see how close it is to the end of the month, i.e. take 31 - 30 = 1, 1 number off so they probably meant 30
EDIT: To answer your question about finding an invalid date check this out: Validate a DateTime in C#
It shows how to detect an invalid date.
To answer your question about how to "guess" which validate date they are closest to I'd say it depends on how you have your date entered. If you do something like have them enter an int value for the day value I'd check to see what the highest day value is for the selected month and then see which one they are closest to (this is just a math operation at this point).
I think this will work
DateTime lastday = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month));

This is an easy way:
//first day of next month
var dt = new DateTime(2015,4,1);
var lastDayOfMonth = dt.AddDays(-1).Day;
As far as delivering a message back to the user, it depends on the environment, technology and preferred approach.

Related

C# set April 1st as start of year

I'm currently working on an app to add data to a SQL table.
One of the fields in the table is for financial month as YYYYMM (e.g. 201805 for August 2018). I need to set this automatically when the row is added as we can't rely on the users to input the correct format.
Is there any way to set DateTime to start the year on 1st April (first day of financial year), or am I going to have to code my way around the issue.
Thanks for all the answers, they did help me solve the problem.
I eventually went with a really simple solution that I probably should have thought of in the first place.
string period = DateTime.Now.AddMonths(-3).ToString("yyyyMM");
What you want is a varchar (or nvarchar) column, with a default that looks something like:
(format(dateadd(month,(-4),getdate()),''yyyyMM'',''en-US''))
But, it appears that SQL Server doesn't like having a default with three functions nested inside each other (two, it seems ok with, but it burps on three). Instead, you can have a Date type column with a default of:
(dateadd(month,(-4),getdate()))
That seems to work, but it's a date 4 months ago. Then just format it correctly whenever you display it.
You could use the following piece of code to get the start of your desired financial year.
var year = DateTime.Now.Year;
DateTime firstDay;
if(DateTime.Now.Month <= 4)
firstDay = new DateTime(year-1, 4, 1);
else
firstDay = new DateTime(year, 4, 1);
There doesn't seem to be a way to do this automatically, but it looks simple enough.

C# Adding years and days in a single DateTime variable

Am I missing something simple?
I am trying to calculate a date 17 years and 364 days before the given date.
Is there a way to do this without converting everything into days? I am trying to avoid dealing with leap years. I am doing the following:
DateTime date = Convert.ToDateTime(tId2);
string tId4a = Convert.ToString(tId4);
var age1 = tId4a.Substring(0, 2);
int age2 = Convert.ToInt32(age1) - 1;
DateTime sub1 = date.AddYears(-age2);
I was hoping to do something simple like:
DateTime sub1 = date.AddYears(-age2) + date.AddDays(-364);
I am being told that I cannot use the '+' in the DateTime.
Sorry, but I am new to this. The reason the age2 variable is used is because at times that value will change. But, the 364 should be consistent. I am creating something to test a date boundary.
Did I overlook something simple?
Thanks.
What you do is you add the "date age2 years ago" to the "date 364 days ago".
Instead do this:
DateTime sub1 = date.AddYears(-age2).AddDays(-364)
This at first subtracts the years and then subtracts the days from the resulting value.
You can't add dates, but you can certainly chain method calls together
date.AddYears(-age2).AddDays(-364);
This is for all intents and purposes the same thing as trying to add them together.
It really sounds like you want to go with tid4 years ago, but go to the next day after that.
The way you are doing it, is that you subtract 1 from that to get age2. Then you subtract that many years, and you also subtract 364 days from your date. This will be more sensitive to leap years. If the resulting date happens to be between Jan 1 and Feb 28 of a leap year, you will end up with one day later than you wanted.
364 is a very suspect number. I tend to think you are using that to mean "the number of days in a year minus one". But the number of days in a year is not always 365. In leap years, the number of days is 366. In such years, subtracting 364 is not 1 day less than a year. It is actually 2 days less than a year, so you would be off.
What you really should do, if I am reading you correct, is to just subtract the number of years, then add one day back in.
DateTime date = Convert.ToDateTime(tId2);
string tId4a = Convert.ToString(tId4);
int age = Convert.ToInt32(tId4a.Substring(0, 2))
DateTime sub1 = date.AddYears(-age).AddDays(1);
I think that it is valuable to mention that DateTime is an object, and that .AddYears(), .AddDays(), etc all return a new DateTime object which is why you cannot add them together like primitive types. So when you run:
DateTime sub1 = date.AddYears(-age2).AddDays(-364);
date.AddYears(-age2) returns a new object, and then .AddDays(-364) is using the new DateTime object and not the date instance.
For more info:
https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx

Strategy for Incomplete Dates

Working on an application where we would like the user to be able to enter incomplete dates.
In some cases there will only be a year - say 1854, or there might be a year and a month, for example March 1983, or there may be a complete date - 11 June 2001.
We'd like a single 'date' attribute/column - and to be able to sort on date.
Any suggestions?
Store the date as an integer -- yyyymmdd.
You can then zero out any month or day component that has not been entered
Year only: 1954 => 19540000
Year & Month: April 2004 => 20040400
January 1st, 2011 => 20110101
Of course I am assuming that you do not need to store any time of day information.
You could then create a struct to encapsulate this logic with useful properties indicating which level of granularity has been set, the relevant System.DateTime, etc
Edit: sorting should then work nicely as well
I can't think of a good way of using a single date field.
A problem you would get if you used January as the default month and 1 as the default day like others have suggested is, what happens when they actually pick January? How would you track if it's a selected January or a defaulted January.
I think you're going to have to store a mask along with the date.
You would only need a bit per part of the date, which would only be 6 bits of data.
M|D|Y|H|Min|S
Month Only 1|0|0|0|0|0 = 32
Year Only 0|0|1|0|0|0 = 8
Month+Year 1|0|1|0|0|0 = 40
AllButMinSec 1|1|1|1|0|0 = 60
You could put this into a Flag Enum to make it easier to use in code.
Well, you could do it via a single column and field that says 'IsDateComplete'.
If you only have the date field, then you'll need to encode the "incompleteness" in the date format itself, such that if the date is, say, < 1900, it's considered "Incomplete".
Personally, I'd go with an field on the side, that marks it as such. Easier to follow, easier to make decisions on, and allows for any dates.
It goes without saying, perhaps, that you can just create a date from DateTime.MinValue and then set what you "know".
Of course, my approach doesn't allow you to "know" what you don't know. (That is, you don't know that they've set the month). You could perhaps use a date-format specifier to mask that, and store it alongside as well, but it's potentially getting cumbersome.
Anyway, some thoughts for you.
One option is to use January as the default month, 1 as the default day, and 1900 or something like that as the default year. Incomplete dates would get padded out with those defaults, and incomplete dates would sort before complete ones in the same year.
Another, slightly more complex option is to use -1 for default day and year, and -1, 'NoMonth', or some such as the default month. Pad incomplete dates as above. This may make sorting a little hard depending on how you do it, but it gives you a way of telling which parts of the date are valid.
I know you'd rather have 1 column but, Instead of a single column one can always have a separate column for day, month and year. Not very difficult to do queries against, and it allways any of the components to be null.
Smehow encoding these states in the datetime itself will be harder to query.
What I did when last solving this problem, was to create a custom date type that kept track of which date parts was actually set and provided conversions to and from a DateTime. For storing in database i used one date field and then one boolean/bit to keep track of which date components that were actually set by the user.

How does .NET determine the week in a TimeZoneInfo.TransitionTime?

Greetings
I'm trying to do some DateTime math for various time zones and I wanted to take daylight savings into account. Lets say I have a TimeZoneInfo and i've determined the appropriate AdjustmentRule for a given DateTime. Lets also say the particular TimeZoneInfo i'm dealing with is specified as rule.DaylightTransitionStart.IsFixedDateRule == false, so I need to figure out if the given DateTime falls within the start/end TransitionTime.Week values.
This is where I'm getting confused, what is .NET considering as a "week"? My first thought was it probably used something like
DayOfWeek thisMarksWeekBoundaries = Thread.CurrentThread.CurrentUICulture.DateTimeFormat.FirstDayOfWeek;
and went through the calendar assigning days to week, incrementing week every time it crossed a boundary. But, if I do this for May 2010 there are 6 week boundary buckets, and the max valid value for TransitionTime.Week is 5 so this can't be right.
Whats the right way to slice up May 2010?
This article http://msdn.microsoft.com/en-us/library/system.timezoneinfo.transitiontime.isfixeddaterule.aspx shows how to extract the IsFixedDateRule == false, see DisplayTransitionInfo
I finally realized whats going on, I think the property name "Week" is what threw me off. There might be 6 weeks in May (depending on how you count them), but any particular DayOfWeek shows up at most 5 times. The Week property doesn't really refer to what week the DayOfWeek is showing up in, its the nth DayOfWeek for that month--with the magic value 5 meaning its last so either the max n is 4 or 5 for a given month.

Building a Datetime Object for SQL database insert

I'm working on a small web form that requires the user to input (among other things), the scheduled backup time of whatever server they're adding to the system. The problem is, I'm struggling to find out the best way to take the user input and build a DateTime object (which is what the database requires).
I only really care about the Day of Week, Time of Day (12 or 24 hour clock).
I thought about just creating an empty DateTime object and then just adding my input values from the user, but you can only get, not set, the day of week, time of day, etc.
I've been looking at the Calender asp control, which would work for the day of the week selection, but I can't seem to find any support of time of day.
Thanks.
I don't think you want to use a DateTime for a recurring event such as a backup. A DateTime is useful for storing a particular date and time, but not a "template" for a recurring event. Instead I'd use separate columns to store the day of week value (0-6) and time of date (minutes after midnight) for the event.
If you going to use datepicker here is one great sample for adding JQuery date picker using C#. That helped me including in my project evrn if I did know anything abaut JQuery and java sripts at all.
DateTime is a immutable value type. You cannot set anything on it.
Assumed that you stick with DateTime on the DB and you don't want to use a DateTimePicker control.
You have to specify how the day of week and the time should be represented in the DateTime. You can start with DateTime.MinValue, the 1.1.0001, 12:00 at midnight, and add the day of week and the time. unfortunately, a regular DateTime field in a SqlServer 2005 is not able to store this date. So lets move it to the year 2000. The 1.1.2000 was a Saturday. You could calculate the DateTime like this:
int dayOfWeek; // 0 = mon, 6 = son
DateTime time;
DateTime scheduleTime = new DateTime(2000, 1, (dayOfWeek + 2) % 6 + 1)
+ time.TimeOfDay;
But honestly, I wouldn't do it. It smells. I just answered your question. Listen to tvanfosson. He said everything that needs to be said.

Categories

Resources