0

Before that, the code was working fine, while the program didn't recognize the date format may be because of different cultureInfo. I am using the Convert.ToDateTime method to convert the DateTime format.

Input.TestDate = Convert.ToDateTime(gvwTest.Rows[i].Cells["TxnDate"].Value).ToString("yyyy-MM-dd HH:mm:ss");

As a result, it converted but with incorrect MM and dd.

From "1/6/2020" To "2020-01-06 00:00:00"

string test1 = gvwTest.Rows[i].Cells["TxnDate"].Value.ToString();
string test2 = gvwTest.Rows[i].Cells["TxnDate"].Value.GetType().ToString();

test1 = "1/6/2020";
test2 = "System.String";
RogerSK
  • 393
  • 1
  • 18
  • 3
    Avoid `Convert.ToDateTime`. Instead you should always prefer `DateTime.ParseExact` and `DateTime.TryParseExact`. Microsoft needs to remove the `Convert` class from .NET entirely, imo. – Dai Jun 01 '20 at 04:16
  • @Dai I didn't know that Microsoft will remove the Convert, but thanks your info. The project has cooperated with many parties, so I just want to make it more standardised. – RogerSK Jun 01 '20 at 04:26

2 Answers2

2

You can use DateTime.ParseExact

CultureInfo provider = CultureInfo.InvariantCulture;
var date = DateTime.ParseExact("1/6/2020", "M/d/yyyy", provider);
var dateString = date.ToString("yyyy-MM-dd HH:mm:ss");

Outputs - 2020-01-06 00:00:00

In my example I have used as input 1/6/2020.

Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • I found that `DateTime.TryParseExact` would be more suitable to solve my problem, however, I will accept this answer as it gives me some clues. Many thanks – RogerSK Jun 01 '20 at 06:22
0

While DateTime.TryParseExact is definitely better way to go as others pointed out already, still Convert.ToDateTime also provides an overload that can accept culture information, in case you want to give it a shot.

Something like this...

Input.TestDate = Convert.ToDateTime(gvwTest.Rows[i].Cells["TxnDate"].Value, CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss");

Or...

Input.TestDate = Convert.ToDateTime(gvwTest.Rows[i].Cells["TxnDate"].Value, CultureInfo.CurrentCulture).ToString("yyyy-MM-dd HH:mm:ss");
Thimmu Lanka
  • 427
  • 3
  • 12