Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello
i want to convert string str to DateTime,str="2024/22/03"
SYSTEMFORMAT of my computer is m/d/yyyy
i want the Date_1 in format yyyy/MM/dd
Date_1 = Convert.ToDateTime(str, "yyyy/MM/dd");

What I have tried:

str = "2024/12/03"; 
Date_1 = Convert.ToDateTime(str, "yyyy/MM/dd");
Posted
Updated 22-Mar-24 6:34am
v2
Comments
PIEBALDconsult 22-Mar-24 12:35pm    
Avoid the Convert class. Use the parsers for the type you want.

DateTime.ParseExact Method (System) | Microsoft Learn[^] will do what you want:
C#
string str = "2024/22/03";

// Parse the string into a DateTime object with the specified format
DateTime dateTime = DateTime.ParseExact(str, "yyyy/dd/MM", null);

// Format the DateTime object into the desired format
string formattedDate = dateTime.ToString("yyyy/MM/dd");

Console.WriteLine("Original string: " + str);
Console.WriteLine("Formatted date: " + formattedDate);

and the output:
Original string: 2024/22/03
Formatted date: 2024/03/22
 
Share this answer
 
To add to what Graeme has said, a better solution is to use DateTime.TryParseExact Method (System) | Microsoft Learn[^] instead - that way you can spot errors instead of your app crashing if the data isn't in the format you expect for some reason:
C#
DateTime dt;
if (!DateTime.TryParseExact(str, "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
   {
   ... report or log the problem
   return;
   }
... dt contains a valid date set at midnight here
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900