PositiveGuy
PositiveGuy

Reputation: 47763

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 send 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.

Upvotes: 2

Views: 5947

Answers (5)

BIDeveloper
BIDeveloper

Reputation: 2638

Concatenate as a string and then convert to a date time.

Upvotes: -2

stimms
stimms

Reputation: 44094

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?

Upvotes: 9

Dan Tao
Dan Tao

Reputation: 128387

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

Upvotes: 0

TLiebe
TLiebe

Reputation: 7996

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

Upvotes: 0

marc_s
marc_s

Reputation: 755157

  1. read all three pieces of information (year, month, day) from the web page into INT variables
  2. replace "Year" with 1900 if empty
  3. create new datetime:

    DateTime myDate = new DateTime(year, month, day)
    

That's about all there is, I think.

Upvotes: 5

Related Questions