Reputation: 1
I Have two type of date formats like 01/05/2018 and 01/may/2018. I want to convert both formats into (dd/MM/yyyy), how do I convert it and save into excel file. I have a problem in saving data into excel, the save not proper format, its change like a month comes first and sometimes date come first the code is:- mystring=mystring.tostring.parse("dd/MM/yyyy")
Upvotes: 0
Views: 703
Reputation: 109
I had similar problem and I tried the code below
DateTime date = DateTime.Now;
string formattedDate = date.ToString("dd'/'MM'/'yyyy");
Upvotes: 1
Reputation: 186803
You can provide several formats
when using DateTime.ParseExact. So you can parse initial string into DateTime
and then format the DateTime
into required format.
string[] tests = new string[] {
"01/05/2018",
"01/may/2018",
};
string[] formats = new string[] {
"d/M/yyyy", // try this format first
"d/MMMM/yyyy", // on fail try this one etc.
};
string[] results = tests
.Select(item => DateTime.ParseExact(item,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal))
.Select(date => date.ToString("dd'/'MM'/'yyyy")) // '/' - to preserve /
.ToArray();
Console.Write(Environment.NewLine, results);
Outcome:
01/05/2018
01/05/2018
Upvotes: 0
Reputation: 3271
I believe you have to do:
targetRange.NumberFormat = "dd/MM/yyyy";
Where targetRange
is either the Cell
or Column
that you want to have the required date format
The format must also be something that Excel understands and this is not always the same as what C# uses
Upvotes: 0