C# set April 1st as start of year - c#

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.

Related

I have the number of days (stored in SQL db as 37867) since 1900 and want to convert it to a date like "Sep-5-2003

I have a number retrieved from SQL = 37867 and need to convert it to the date it represents which is 2003-09-05.
The number 37867 represents the number of days since 1900 and the answer should be 2003-09-05 but how to calculate this in C#?
This is the SQL function that does it: "SELECT CONVERT(datetime,37867)" but how can I do it in C# so I can update that int and make it a string literal and replace that int with that string?
I am guessing that this is how the struct for Windows stores the DateTime stamp.
If I spend enough time I am pretty sure I can figure it out, but it will take more time than I really want to spend and if someone else already has...why re-invent the wheel?
This community generally prefers that you make an attempt, if we see what you were attempting to do it's generally easier to help then writing something from scratch.
Having said that:
// Create new DateTime, January 1st 1900
var dt = new DateTime(1900, 1, 1);
// Add 37867 days to that DateTime
dt = dt.AddDays(37867);
// Call ToString()
var s = dt.ToString();

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

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.

How to string year to datetime in sql server

I have a textbox without calendar control and we will call it as publication year(we use diff name in our project). The publication year is 1999, 2001 or 1860.
My step goes like this
I have datetime in my database.(unchangable)
I am using C# and sql server 2005.
string date = textBox1.text;
Datetime dt = Convert.ToDateTime(date);
I pass dt to my database using dynamic sql
to trick the code, I added a prefix 1/1/ before my entered date like 1/1/2010 , it worked well
Now my TL asked me not to do like that.... I am ??? . Please help
It sounds like you should really:
Parse the text as an integer
Create a new DateTime with that year, and January 1st as the day/month.
For example:
int year;
if (int.TryParse(textBox1.Text, out year))
{
DateTime dt = new DateTime(year, 1, 1);
}
else
{
// Handle input
}
As a note, if you only care about the year then I would highly suggest that the database field should be an Int instead of a DateTime.
The minimum sql datetime value is 1/1/1753 for a number of reasons that you can certainly look up. However, the point is that a regular DateTime field is storing way more information than you care about.
So if you deal with publications older than 1753 you're going to run into an architectural issue. And, if somehow you didn't, you'd certainly run into issues deciding if a publication was 280 years old or 279 or 281...
You could use a drop down list with the available years? If there are only three possible publication years, then this would make more sense as an input control. Grab the year and pad the DateTime month and day values with "1" each.

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.

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