1

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;

3 Answers3

3

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.

mm8
  • 163,881
  • 10
  • 57
  • 88
0

Can you try this?

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

redevilliers
  • 75
  • 1
  • 6
0

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}");
Greg
  • 11,302
  • 2
  • 48
  • 79