简体   繁体   中英

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;

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.

Can you try this?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM