0

i want to convert Datetime. I don't know how to do this? It gives errors. nvarchar doesn't convert to datetime.

startDate format : "11.03.2012"

My table : STARTDATE datetime ENDDATE datetime

public static int Insert(string startDate, string endDate)
{

    Conn c = new Conn();
    SqlParameter[] prms = new SqlParameter[]{
    new SqlParameter("@STARTDATE", DateTime.ParseExact(startDate,"DD MM YYYY",null)),
    new SqlParameter("@ENDDATE",  DateTime.ParseExact(endDate,"DD MM YYYY",null)),        
    };

    return Convert.ToInt32(c.getObjectSP("sp_Insert", prms));
}
ozkank
  • 1,464
  • 7
  • 32
  • 52
  • If you already know what the format is that your input comes in, why do you use a different mask when trying to parse it? Also, what is a Conn? – Mr Lister Mar 12 '12 at 13:52
  • You can look at here. http://stackoverflow.com/questions/425870/using-datetime-in-a-sqlparameter-for-stored-procedure-format-error – Sinan AKYAZICI Mar 12 '12 at 13:53
  • When you say "It gives errors", you should post the details of these errors. – Oded Mar 12 '12 at 14:01

2 Answers2

3

With a date that is formatted like "11.03.2012", you need to parse with the . in your format string.

DateTime.ParseExact(startDate,"dd.MM.yyyy",null)

Also note that DD and YYYY are not characters that are identified in the format string as parts of the datatime but are expected to be literals. See my example - dd for 2 characters for days and yyyy for 4 characters for year.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

This is a nice article about it: http://www.csharp-examples.net/string-format-datetime/

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone
Andrew
  • 7,619
  • 13
  • 63
  • 117