简体   繁体   中英

How can I convert decimal? to string?

I'm writing an ASP.NET MVC program in C# and I have a date fetched from my database, but the date is set as a decimal type, and I can't change that. I need to know how I can format the decimal to look like 04/15/2017 instead of 20170415.00

This is how that column is declared in my model.

public decimal? SIM2_DUE_DATE { get; set; }

I'm calling the date from the database. I have over 1000 dates that need to be formatted. I just used that one as an example, so I can't format it specifically.

You can use math to convert your "date" to DateTime type. First spilt it into parts like this:

var date = 20170415.00M;
var year = (int)date / 10000;
var month = (int) date / 100 % 100;
var day = (int)date % 100;

then call a DateTime constructor:

var dateTime = new DateTime(year, month, day);

You could do this by using DateTime.ParseExact :

string dueDate = SIM2_DUE_DATE.ToString("D"); // remove decimals
var parsedDate = DateTime.ParseExact(dueDate, "yyyyMMdd", CultureInfo.InvariantCulture); // parse the date and ensure it's in that specific format
var display = parsedDate.ToShortDateString(); // get the culture-specific date representation

Notice that this would fail if you kept the decimals

Considering your date in decimal value

decimal dtdec = 20170415.00M;

You have few options

                var newDate = DateTime.ParseExact(((Int64)dtdec).ToString(),
                                      "yyyyMMdd",
                                       System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(newDate.ToShortDateString());

Or

Console.WriteLine(DateTime.Parse(dtdec.ToString("####/##/##")));

Or

Console.WriteLine(dtdec.ToString("####/##/##"));
Decimal decimalDateValue = 20170105.00;
DateTime dateEquivalent = DateTime.MinValue;
DateTime.TryParse(decimalDateValue.ToString(),out dateEquivalent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM