ozkank
ozkank

Reputation: 1462

converting datetime

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));
}

Upvotes: 0

Views: 260

Answers (2)

Andrew
Andrew

Reputation: 7778

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

Upvotes: 2

Oded
Oded

Reputation: 499002

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.

Upvotes: 3

Related Questions