我该如何转换小数?串?

时间:2018-03-15 17:56:18

标签: c#

我在C#中编写了一个ASP.NET MVC程序,我从我的数据库中获取了一个日期,但是日期设置为十进制类型,我无法改变它。我需要知道如何将小数格式设置为04/15/2017而不是20170415.00

这就是我的模型中声明该列的方式。

public decimal? SIM2_DUE_DATE { get; set; }

我从数据库中调用日期。我有超过1000个日期需要格式化。我只是用那个作为例子,所以我不能专门对它进行格式化。

4 个答案:

答案 0 :(得分:5)

您可以使用数学转换您的"日期"到DateTime类型。首先把它分成这样的部分:

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

然后调用DateTime构造函数:

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

答案 1 :(得分:1)

您可以使用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

请注意,如果保留小数

,则会失败

答案 2 :(得分:0)

以十进制值考虑您的日期

decimal dtdec = 20170415.00M;

你有几个选择

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

或者

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

或者

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

答案 3 :(得分:0)

Decimal decimalDateValue = 20170105.00;
DateTime dateEquivalent = DateTime.MinValue;
DateTime.TryParse(decimalDateValue.ToString(),out dateEquivalent);