Click here to Skip to main content
15,670,482 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
string Fulldate = Request["msgDate"]; //"3/17/2014 10:32:35 AM"
            string SDate = string.Format("{0:yyyy-mm-dd}", Fulldate); // its not converting to 2014-03-17
Posted

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
 
Comments
Marcin Kozub 17-Mar-14 7:26am    
+5
Peter Leow 17-Mar-14 7:36am    
Thank you Marcin.
It's beacuase you're passing string to string.Format method.
FullDate variable must be DateTime object.
C#
DateTime Fulldate = Request["msgDate"]; //"3/17/2014 10:32:35 AM"
string SDate = string.Format("{0:yyyy-mm-dd}", Fulldate);


Hope it help you.
 
Share this answer
 
v2
Comments
[no name] 17-Mar-14 7:13am    
DateTime Fulldate = Request["msgDate"];

I am getting this error:
Cannot implicitly convert type 'string' to 'System.DateTime'
Marcin Kozub 17-Mar-14 7:26am    
It's because Request["msgDate"] returns string. You need to convert it to DateTime and then format it the way you want. Please, look at Solution 2, Peter Leow explained very well how to parse string to DateTime.
Thomas Daniels 17-Mar-14 13:46pm    
I think your comment is meant as a reply to the comment of the OP. If it is a reply, use the "Reply" button to post a reply instead of the "Have a Question or Comment?" button.
Marcin Kozub 17-Mar-14 16:09pm    
Yup, thx. Wrong button :)
Use this link http://www.csharp-examples.net/string-format-datetime/</a>[^]
It will definitely help you.
 
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