Reputation: 51
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.
Upvotes: 1
Views: 1025
Reputation: 3169
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("####/##/##"));
Upvotes: 0
Reputation: 109
Decimal decimalDateValue = 20170105.00;
DateTime dateEquivalent = DateTime.MinValue;
DateTime.TryParse(decimalDateValue.ToString(),out dateEquivalent);
Upvotes: 0
Reputation: 32068
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
Upvotes: 1
Reputation: 7054
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);
Upvotes: 5