Matthew Almeida
Matthew Almeida

Reputation: 23

Error while converting string to datetime in c#

I have a DateTime, i'm trying to convert it to string, then convert it back to DateTime to format it. But i keep getting "string isn't recognized as valid datetime string". Any ideas?

var data = list_2.Entries.Select(c => new clients { code = cli_code, last_backup = c.Name, last_backup_date = c.AsFile.ClientModified.ToLocalTime() }).LastOrDefault(); 
var last_backup_date = data.last_backup_date;
var last_backup_date_string = Convert.ToString(last_backup_date);
var last_backup_date_formatted = DateTime.ParseExact(last_backup_date_string, "dd/MM/yyyy HH:MM:ss", CultureInfo.InvariantCulture);
var today_date = DateTime.Today;

Upvotes: 1

Views: 133

Answers (3)

Greg
Greg

Reputation: 11478

Based on the information you have, the conversion should not be an issue. However, the problem area is probably in your ParseExact. Your current date format starts with month not the day. You should be able to do the format to display in your preferred manner.

Console.WriteLine($"{date.ToString("dd/MM/yyyy")}");
Console.WriteLine($"{date.ToString("MMMM dd, yyyy")}");
Console.WriteLine($"{date.ToString("MM-dd-yyyy")}");

Otherwise you could use the DateTime.Parse method or DateTime.TryParse so you do not have to specify the culture variation.

Example:

DateTime date;
var current = DateTime.Now.ToString();
if(DateTime.TryParse(current, out date))
     Console.WriteLine(date);

DateTime date;
var current = "6/22/2020 10:03:40 AM";
if(DateTime.TryParse(current, out date))
     Console.WriteLine($"{date:dd/MM/yyyy}");

Upvotes: 0

mm8
mm8

Reputation: 169400

Since you already have a DateTime, you could just format it:

string s = last_backup_date.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

There is no need to first convert it to a string and then try to convert it back to a DateTime. A DateTime object itself has no specific format by the way.

Upvotes: 3

redevilliers
redevilliers

Reputation: 75

Can you try this?

Var last_backup_date_string = last_backup_date.ToString("dd/MM/yyyy HH:MM:ss", CultureInfo.InvariantCulture)

Upvotes: 0

Related Questions