I am trying to convert a DateTime?
value to Decimal
. (Note: that DateTime?
is Nullable
)
From this format 4/1/2011 12:00:00 AM
to this format (of Decimal
type) 20110401
.
How can this be achieved?
I am trying to convert a DateTime?
value to Decimal
. (Note: that DateTime?
is Nullable
)
From this format 4/1/2011 12:00:00 AM
to this format (of Decimal
type) 20110401
.
How can this be achieved?
Like this:
DateTime? myDateTime = GetDateTime();
Decimal.Parse(myDateTime.Value.ToString("yyyyMMdd"));
or:
DateTime myDateTime = GetDateTime();
Decimal.Parse(myDateTime.ToString("yyyyMMdd"));
Depending on if DateTime
is Nullable
or not.
But you really should consider storing it in some other fashion than Decimal
it would be like storing a phone number as a Long
, which you really shouldn't do. Mainly because mathematical operations don't make sense when performed on an object stored this way.
You may try this,,
DateTime? dateTime = DateTime.Today;
string dateStr = dateTime.ToString("MMddyyyy");
decimal dec = Convert.ToDecimal(dateStr);
You can do this with a little math:
DateTime? dt = DateTime.Today;
decimal d = dt.Value.Year*10000 + dt.Value.Month*100 + dt.Value.Day
...or convert it:
DateTime? dt = DateTime.Today;
decimal d = Convert.ToDecimal(dt.Value.ToString("yyyyMMdd"));
In case, you try to use this decimal value for sorting purposes, please consider that it is possible to order strings and DateTimes, too.
You can use ToBinary()
to get a binary representation of the DateTime
- this can, then, be assigned to a decimal
.
DateTime dt = DateTime.Now;
decimal dec = dt.ToBinary ();
This is the most straightforward conversion that doesn't involve converting to a string and back. If you're using a nullable date/time, just use the Value
property to get the actual value out of it (with error checking, etc.)