Manually putting together parts of a date
Ok, I'm not quite sure how to go about this. Here's the scenario.
1) On a web form we have 3 dropdowns: Month, Day, and Year
2) Year is always optional (not required)
3) If the customer enters month and day, and not year, we want to default the year to 1900
4) If the customer does enter all 3, I need to piece together a DateTime to represent that. Either way, the year is going to have something...either a valid year or 1900 if the user did not select year.
So in my code-behind, I'm not quite sure how to set all this up. Ultimately I need to form that date so I can update the SQL 2008 Date datatype once I sen开发者_如何转开发d down the date to my DL update function.
So I created a DataTime variable in my code-behind method that picks up the values that the user has selected in each dropdown. However I guess there's no setter on DateTime.Year and so fourth. So I can't just do DateTime.year = "1900" or something to that effect.
You're right that there is no setter but these can all be set in the constructor. You might do something like
DateTime date = new DateTime(year.HasValue ? year.Value : 1900, month, day)
Where year is an Int32?
- read all three pieces of information (year, month, day) from the web page into INT variables
- replace "Year" with 1900 if empty
create new datetime:
DateTime myDate = new DateTime(year, month, day)
That's about all there is, I think.
There's a DateTime constructor that takes a year, month and a day as it's input parameters. You can use that and put in the values from your dropdowns (defaulting to 1900 if no year is selected).
It is also in fact possible to change the year of a DateTime
after constructing it, though it is somewhat more laborious:
int yearsSinceNineteenHundred = date.Year - 1900;
date = date.AddYears(-yearsSinceNineteenHundred);
Concatenate as a string and then convert to a date time.
精彩评论