-1

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");

}

Jim G.
  • 15,141
  • 22
  • 103
  • 166
  • 1
    Instead of Convert.ToDateTime, use [DateTime.TryParseExact](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-5.0#System_DateTime_TryParseExact_System_String_System_String___System_IFormatProvider_System_Globalization_DateTimeStyles_System_DateTime__) passing an array of possible formats for the input value. At that point, if TryParseExact succeed in converting the original string in a DateTime variable you can get back a string with the format required just using ToString("dd-MMM-yyyy") on the date converted by TryParseExact – Steve Jun 06 '21 at 12:08
  • Is this the way? – Konda Reddy Jun 06 '21 at 12:12
  • DateTime? dt1 = null, dt2 = null; string StartDate = null, EndDate = null; if (audit.FromDate != null) { dt1 = DateTime.TryParseExact(audit.FromDate.ToString(), "dd/MMM/yyyy",CultureInfo.InvariantCulture).ToString("dd/MMM/yyyy") ; StartDate = dt1.ToString().Substring(0, 10); } – Konda Reddy Jun 06 '21 at 12:12
  • The point is: What is the type of audit.FromDate? If it is a string and you don't control how this string is written then you can only use TryParseExact with an array of the possible formats. Not complete but you can get good enough results – Steve Jun 06 '21 at 12:14
  • The type is DateTime format – Konda Reddy Jun 06 '21 at 12:17
  • If FromDate is already a date then no need to convert anything. If you need a string in a specific format just ask to the FromDate to give you a string in the format required audit.FromDate.ToString("dd-MMM-yyyy") – Steve Jun 06 '21 at 12:18
  • `var stringValue = dt1?.ToString("dd-MMM-yyyy");` – mjwills Jun 06 '21 at 12:40
  • A value of type DateTime doesn't *have* a format, it is some binary value. Only when you convert it to a string ( such as displaying in a debugger) a format can be applied. But then it's a string, not a DateTime anymore – Hans Kesting Jun 06 '21 at 13:54

3 Answers3

2

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

pinkfloydx33
  • 11,863
  • 3
  • 46
  • 63
1

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.

  • This is not working getting error. ` DateTime? dt1 = null, dt2 = null; string StartDate = null, EndDate = null; if (audit.FromDate != null) { dt1 = Convert.ToDateTime(audit.FromDate); StartDate = dt1.ToString("dd-MMM-yyyy"); } ` – Konda Reddy Jun 06 '21 at 12:01
  • 1
    Use DateTime.TryParse to convert. And please share the error message. – Afshin Mobayen Khiabani Jun 06 '21 at 12:03
  • Is this the way? DateTime? dt1 = null, dt2 = null; string StartDate = null, EndDate = null; if (audit.FromDate != null) { dt1 = DateTime.TryParseExact(audit.FromDate.ToString(), "dd/MMM/yyyy",CultureInfo.InvariantCulture).ToString("dd/MMM/yyyy") ; StartDate = dt1.ToString().Substring(0, 10); } – Konda Reddy Jun 06 '21 at 12:13
1

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.

  • This is not working getting error. ` DateTime? dt1 = null, dt2 = null; string StartDate = null, EndDate = null; if (audit.FromDate != null) { dt1 = Convert.ToDateTime(audit.FromDate); StartDate = dt1.ToString("dd-MMM-yyyy"); } ` – Konda Reddy Jun 06 '21 at 11:59
  • 2
    @KondaReddy because a date **has no format**. It only has a format **when displayed** (convert to a string). You also cannot assign a string back to a date variable like you are attempting to do in your comment. If you want it output in a specific format, use "ToString" *at that point*. But if using excel set the value to the date object **as a date** and then *set the cell formatting* instead – pinkfloydx33 Jun 06 '21 at 12:41