简体   繁体   English

如何转换小数? 串起来?

[英]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. 我正在用C#语言编写一个ASP.NET MVC程序,并且有一个从数据库中获取的日期,但是该日期设置为十进制类型,因此无法更改。 I need to know how I can format the decimal to look like 04/15/2017 instead of 20170415.00 我需要知道如何格式化小数使其看起来像20170415.00 04/15/2017而不是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. 我有1000多个日期需要格式化。 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. 您可以使用数学将“日期”转换为DateTime类型。 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: 然后调用DateTime构造函数:

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

You could do this by using DateTime.ParseExact : 您可以使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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