English 中文(简体)
将日期格式转换为 mm-dd-yyyyyyyyy
原标题:Convert date format to mm-dd-yyyyy

我正用日期来填充列表“ 结果 ” 。 在查询结果中, 我正在获取一系列的值 。 日期值是在这个格式中 。

201205100000000

在我的代码,我做以下...

    query = service.GetData();
    List<String> results = new List<String>();
    foreach (var item in query)
    {
        results.Add(item.InDate);  
        //This is in this format - 201205100000000
        //Here I want to convert to mm-dd-yyyy                              
    }
    return results;

我希望将上述日期格式转换为“mm/dd/yyyyyy”并张贴到“结果”列表。

最佳回答

如果保证日期为[年][月][日][日][小时][分钟][分钟][第二 [二年]格式(看起来类似),您可以使用简单的字符串操作:

var newDate = item.InDate.Substring(2, 2) + "-" +
              item.InDate.Substring(4, 2) + "-" +
              item.InDate.Substring(0, 4);

如果您想要在 DateTime 对象中找到它,请使用 DateTime.Professact 方法:

var newDate = DateTime.ParseExact(indate, "yyyyMMddHHmmssfff", CultureInfo.InvariantCulture);
问题回答
query = service.GetData();
    List<String> results = new List<String>();
    foreach (var item in query)
    {
        var unformattedDate = item.InDate;
        var formattedDate = DateTime.ParseExact(unformattedDate,
                                    "yyyyMMddHHmmssfff",
                                    System.Globalization.CultureInfo.InvariantCulture)
        results.Add(formattedDate);                              
    }
    return results;

以上提供的答案是正确的。 最好保存您要显示的日期和日期格式的格式, 并保存在配置文件或资源文件中。 这对于硬码不好 。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签