Click here to Skip to main content
16,004,836 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

I need to change the string to Date format in c#

i.e 2/22/2014 5:08:46 PM to 2014-02-22.

Thanks
GSS
Posted
Comments
CHill60 22-Feb-14 9:27am    
2014-02-22 is not a date format (there isn't one in C# it's DateTime). Are you saying that you have something like string dt = "2/22/2014 5:08:46 PM"; or do you have DateTime dt; with a value of '2/22/2014 5:08:46 PM' and you want to format the latter without the time?
Gssankar 22-Feb-14 9:40am    
Thanks Chill for your reply.

string recDate = 2/22/2014 5:08:46 PM; I need time also.


1. First, check that the date string is a valid one using tryparse;
2. Specify the desired date format;
3. then can do the conversion.

C#
using System;

public class Program
{
    public static void Main()
    {
          // change 2/22/2014 5:08:46 PM to 2014-02-22.
          string dateString = "2/22/2014 5:08:46 PM";

          Console.WriteLine("The original string is {0}", dateString);

          DateTime dt;

          if (DateTime.TryParse(dateString, out dt))
          {
               string format = "yyyy-MM-dd";
               Console.WriteLine(dt.ToString(format));
          }
          else
          {
              Console.WriteLine("Not a valid datetime");
          }
    }
}
 
Share this answer
 
v2
C#
// String to DateTime
 String MyString;
 MyString = "2/22/2014 5:08:46 PM";

 DateTime MyDateTime;
 MyDateTime = new DateTime();
 MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm", null);

A very good article found on CodeProject, Easy String to DateTime, DateTime to String and Formatting[^] and yes, MSDN[^] as well.

-KR
 
Share this answer
 
v2
Comments
Gssankar 22-Feb-14 9:52am    
Thanks Rohit for your reply.
But I have received this Error

String was not recognized as a valid DateTime.
Krunal Rohit 22-Feb-14 12:33pm    
Answer is updated, take a look.

-KR
C#
//Finally, I cleared my solution.
string  recDate = "2/22/2014 5:08:46 PM";
DateTime dr = Convert.ToDateTime(recDate);
object s = String.Format("{0:u}", dr); 
 
Share this answer
 
v2
Comments
CHill60 22-Feb-14 10:46am    
You would be better off using one of the DateTime parse methods rather than Convert - TryParse would be my choice.

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