-3

I have 3 integer values and I'm trying to combine them to create a datetime variable. I'm trying to do this as I'm needing the user to specify the year through a datetimepicker and then in an array I need the date to start at the first day of the first month of that year.

Currently I have,

int b = 1;
int m = 1;
int y = dateTimePicker1.Value.Year;

DateTime newdate = new DateTime(b, m, y);

I've tried a whole range of different ways of combing the integers together to form 1/1/2017. I know that the integers are holding the correct values when the error appears, but the newdate value is 01/01/0001 12:00:00:AM.

I don't know why the integer y is being changed from 2017 to 0001?

As a result the error message is, Year, Month and Day parameters describe an un-representable DateTime.

Jim
  • 2,974
  • 2
  • 19
  • 29
Loplac92
  • 63
  • 7

2 Answers2

1

First you need to change parameter order

 DateTime newdate = new DateTime(year, month, day);

Second you can use DateTime.Parse or DateTime.TryParse to get date object from string

Jacek
  • 11,661
  • 23
  • 69
  • 123
  • Could you improve the formatting of the `DateTime.Parse` and `DateTime.TryParse` to make it easier to read and recognise as code. Other than that +1 – Zach Ross-Clyne Nov 16 '16 at 13:31
1

You have the parameters in the wrong order.

The order is year, month, day:

var newDate = new DateTime(y, m, b);

You are trying to create the date 2017/1/1 which is not valid.

MSDN page

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • Consider using `DateTime newDate` as `var` is bad practice on variable types that have short names as the code is more understandable when using the actual data type when declaring the variable – Zach Ross-Clyne Nov 16 '16 at 13:29
  • 2
    @ZachRoss-Clyne - do you have a reference for that? Given that ReSharper (for example) doesn't make this distinction when suggesting that I use `var` rather than the type I find your statement hard to believe. – ChrisF Nov 16 '16 at 13:31
  • 2
    @ZachRoss-Clyne that is pure preference and doesn't add any improvement to the solution. – Jim Nov 16 '16 at 13:32
  • http://stackoverflow.com/a/4050566/1704725 Just makes it easier to read thats all and as its not a massive difference in characters it would be silly to make it less easy to read – Zach Ross-Clyne Nov 16 '16 at 13:33
  • 1
    @ZachRoss-Clyne that answer is purely someone's personal preference and in no way determines what's good or bad practice. – ChrisF Nov 16 '16 at 13:34
  • Try this one https://blogs.msdn.microsoft.com/ericlippert/2011/04/20/uses-and-misuses-of-implicit-typing/ – Zach Ross-Clyne Nov 16 '16 at 13:37
  • @ZachRoss-Clyne Did you even read that because nothing there supports your claim that this case is a bad use of `var`. In fact he actually supports this case _Use var when the type of the declaration is obvious from the initializer, especially if it is an object creation. This eliminates redundancy._ – juharr Nov 16 '16 at 13:40