Click here to Skip to main content
14,207,436 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
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
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

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.
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");
          }
    }
}
   
Comments
Marcin Kozub 17-Mar-14 7:26am
   
+5
Peter Leow 17-Mar-14 7:36am
   
Thank you Marcin.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

It's beacuase you're passing string to string.Format method.
FullDate variable must be DateTime object.
DateTime Fulldate = Request["msgDate"]; //"3/17/2014 10:32:35 AM"
string SDate = string.Format("{0:yyyy-mm-dd}", Fulldate);


Hope it help you.
   
v2
Comments
Mohammed_Faisal_Majeed 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 :)
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

Use this link http://www.csharp-examples.net/string-format-datetime/</a>[^]
It will definitely help you.
   

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



Advertise | Privacy | Cookies | Terms of Service
Web05 | 2.8.190612.1 | Last Updated 17 Mar 2014
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100