简体   繁体   English

Convert.ToDateTime('Datestring') 到所需的 dd-MMM-yyyy 日期格式

[英]Convert.ToDateTime('Datestring') to required dd-MMM-yyyy format of date

I'm trying to export to excel I have string of Date which can be in any format of date but I wanted to convert it to dd-MMM-yyyy format.我正在尝试导出到 excel 我有日期字符串,可以是任何日期格式,但我想将其转换为 dd-MMM-yyyy 格式。 I have tried every Convert.ToDatetime option which converts only to the System format.我已经尝试了每个 Convert.ToDatetime 选项,它只转换为系统格式。 I want it to convert dd-MMM-yyyy format.我希望它转换 dd-MMM-yyyy 格式。

Thanks Inadvance.提前致谢。

List<UnavailableModel> collection = UnavailableBL.GetAllUnavailableDetails(FilteredFacetsJsonString).Result.ToList();
base.Warning(string.Format("Get {0} number of records ", collection.Count));
List<object> obj = new List<object>();
obj.Insert(0, new string[7] { "NAME", "REGION NAME", "MANAGER NAME", "FROM DATE", "TO DATE", "CATEGORY", "COMMENTS" });

int count = 1;
foreach (var audit in collection)
{
    DateTime? dt1 = null, dt2 = null;
    string StartDate = null, EndDate = null;
    if (audit.FromDate != null)
    {
        dt1 = Convert.ToDateTime(audit.FromDate);
        StartDate = dt1.ToString().Substring(0, 10);
    }
    if (audit.ToDate != null)
    {
        dt2 = Convert.ToDateTime(audit.ToDate);
        EndDate = dt2.ToString().Substring(0, 10);
    }
    obj.Insert(count, new string[7]{
        string.Format("\"{0}\"", audit.Region_Name),
        string.Format("\"{0}\"",  audit.First_Name+" 
        "+audit.Last_Name),
        string.Format("\"{0}\"", audit.Manager_First_Name+" "+audit.Manager_Last_Name),
        string.Format("\"{0}\"", StartDate),
        string.Format("\"{0}\"", EndDate),
        string.Format("\"{0}\"", audit.Category),
        string.Format("\"{0}\"", audit.Comments)
    });
    count++;
}
base.Warning(string.Format("Data table created "));


for (int i = 0; i < obj.Count; i++)
{
   string[] stringCSV = (string[])obj[i];
   for (int j = 0; j < stringCSV.Length; j++)
   {
       //Append data with separator.
       sb.Append(stringCSV[j] + ',');
   }

   //Append new line character.
   sb.Append("\r\n");

}

First, a DateTime has no format .首先, DateTime没有 format It is stored internally as an integer representing the number of ticks since 1/1/0001.它在内部存储为 integer 代表自 0001 年 1 月 1 日以来的滴答数。 A DateTime only "has a format" when displayed . DateTime在显示时“具有格式”。 And that's only after it's been converted to a string (whether by using the default formatting of the current culture or one you specify explicitly when calling ToString ).只有在它被转换为string之后(无论是使用当前文化的默认格式,还是在调用ToString时明确指定的格式)。

Second, this line is pointless:其次,这条线毫无意义:

dt1 = Convert.ToDateTime(audit.FromDate);`

As FromDate is already a DateTime , all you would need to do is assign it directly :由于FromDate已经DateTime ,您需要做的就是直接分配它:

dt = audit.FromDate;

But you're mixing things up.但是你把事情搞混了。 You cannot assign a formatted Date (a string ) to a DateTime variable.您不能将格式化的 Date ( string )分配给DateTime变量。 Format your Date as a string and store it as a string variable and pass that to your Excel building method:将您的日期格式化为string并将其存储为string变量并将其传递给您的 Excel 构建方法:

string EndDate = audit.FromDate.ToString("dd-MMM-yyyy");

There is absolutely no need for DateTime.Parse , DateTime.TryParse , DateTime.TryParseExact or Convert.ToDateTime in your code.您的代码中绝对不需要DateTime.ParseDateTime.TryParseDateTime.TryParseExactConvert.ToDateTime You have everything you need already without performing any uncecessary "conversions".您已经拥有了所需的一切,而无需执行任何不必要的“转换”。

If you have the DateTime in hand you can write that as string in excel like below:如果您手头有 DateTime,则可以将其写为 excel 中的字符串,如下所示:

StartDate = dt1.ToString("dd-MMM-yyyy");

Then use that string to enter excel.然后使用该字符串输入 excel。

Just to expand a bit on Afshin's practical solution.只是为了扩展Afshin 的实用解决方案。 There are quite a bit of resources and questions on this problem.关于这个问题有很多资源问题 Generally, when formatting the string from an object, the ToString method is your friend.通常,当从 object 格式化字符串时, ToString方法是您的朋友。 In the case of a date, you can pass in the custom format that you want as a string:对于日期,您可以将所需的自定义格式作为字符串传递:

StartDate = dt1.ToString("dd-MMM-yyyy");

Keep in mind that it's usually safer to use DateTime.TryParse when dealing with external resources.请记住,在处理外部资源时使用DateTime.TryParse通常更安全。 Here's some guidance on the subject.这是有关该主题的一些指导

暂无
暂无

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

相关问题 将.ToDateTime(&#39;Datestring&#39;)转换为日期所需的dd-MM-yyyy格式 - Convert.ToDateTime('Datestring') to required dd-MM-yyyy format of date 将字符串转换为Datetime格式dd-MMM-yyyy问题 - Convert string to Datetime format dd-MMM-yyyy issue C#Convert.ToDateTIme函数是否将日期读为“dd / mm / yyyy”或“mm / dd / yyyy”? - Does the C# Convert.ToDateTIme function read date as “dd/mm/yyyy” or “mm/dd/yyyy”? 将日期格式从 dd-mmm-yyyy (16-May-2013) 转换为 mm/dd/yyyy (09/12/2013) - Convert Date format from dd-mmm-yyyy (16-May-2013) to mm/dd/yyyy (09/12/2013) 如何将日期格式从dd-MMM-yyyy更改为yyyy-MM-dd - how to change date format from dd-MMM-yyyy to yyyy-MM-dd 如何告诉convert.todatetime输入格式为dd-mm-yyyy - how to tell convert.todatetime that the input is in format dd-mm-yyyy 具有日期格式dd / MM / yy的DateTime.TryParseExact或Convert.ToDateTime()的范围是多少 - what is the range of DateTime.TryParseExact or Convert.ToDateTime() having date format dd/MM/yy FileHelpers Csv阅读器 - 无法转换dd-mmm-yyyy日期时间格式 - FileHelpers Csv reader - Failing to convert dd-mmm-yyyy DateTime Format 使用bg-BG文化和dd-MMM-yyyy格式解析11月的日期时间。 - Parsing a date time in november using bg-BG culture and dd-MMM-yyyy format. 如何在C#中执行Convert.ToDateTime或解析日期,但在C#2.0中仅获得dd / mm / yyyy? - How to do Convert.ToDateTime or parse date in C# but only get dd/mm/yyyy in C# 2.0?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM