0

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?

Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48
Nakres
  • 1,212
  • 11
  • 27

4 Answers4

1

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.

ScottishTapWater
  • 3,656
  • 4
  • 38
  • 81
1

You may try this,,

DateTime? dateTime = DateTime.Today;
string dateStr = dateTime.ToString("MMddyyyy");
decimal dec = Convert.ToDecimal(dateStr);
Akram Qalalwa
  • 103
  • 11
0

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.

Jules
  • 567
  • 1
  • 6
  • 15
0

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

xxbbcc
  • 16,930
  • 5
  • 50
  • 83