简体   繁体   中英

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. I have tried every Convert.ToDatetime option which converts only to the System format. I want it to convert dd-MMM-yyyy format.

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 . It is stored internally as an integer representing the number of ticks since 1/1/0001. A DateTime only "has a format" when displayed . 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 ).

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 :

dt = audit.FromDate;

But you're mixing things up. You cannot assign a formatted Date (a string ) to a DateTime variable. Format your Date as a string and store it as a string variable and pass that to your Excel building method:

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. 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:

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

Then use that string to enter excel.

Just to expand a bit on Afshin's practical solution. 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. 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. Here's some guidance on the subject.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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