I am having a field type DateTime in SQL server database. I am developing a webservice to fetch date and time.
The date is stored in this format 4/14/2013 10:10:01 PM in database.
Now, I have a webmethod as below:
public string GetdataJson(string lastdate)
{
DateTime myDateTime = DateTime.Parse(lastdate);
string getvalue = "select * from tblfameface where last_updated >='" + myDateTime + "'";
con1 = new SqlConnection(conString1);
con1.Open();
SqlCommand cmd = new SqlCommand(getvalue, con1);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt1 = new DataTable();
da.Fill(dt1);
string jsonString = JsonConvert.SerializeObject(dt1);
String finalString = "{\"Records\":";
finalString += jsonString;
finalString += "}";
return finalString;
}
But this code is giving me an error of String was not recognized as a valid DateTime. how can I convert string into datetime format like 4/14/2013 10:10:01 PM?? help!
You want 12-hour clock use small hh , You want the 24-hour clock use capital HH
DateTime formatted =Covert.ToDateTime( lastdate.ToString("dd/MM/yyyy hh:mm:ss.fff",
CultureInfo.InvariantCulture));
If you want to use the 12-hour clock, use tt in the format string to produce the AM/PM designator.
In your format string use tt
for PM/AM part. Here is the code:
DateTime dateTime =
DateTime.ParseExact("4/14/2013 10:10:01 PM",
"M/dd/yyyy hh:mm:ss tt",
System.Globalization.CultureInfo.InvariantCulture);
This should also works:
DateTime result = DateTime.Parse("04/14/2013 10:10:01 PM");
Are you sure you are getting the correct string?
使用此代码
DateTime.ParseExact(yourString, "MM/dd/yyyy hh:mm:ss tt");
Try this:
string getvalue = "select * from tblfameface where
last_updated >= Convert(DateTime, '" + myDateTime + "')";
or this depending on you SQL data type on column last_updated
string getvalue = "select * from tblfameface where
last_updated >= Convert(DateTime2(7), '" + myDateTime + "')";
Replace query line by
string getvalue = "select * from tblfameface where CAST(last_updated AS
DATETIME)>='" + myDateTime.ToString("dd/MM/yyyy hh:mm:ss tt") + "'";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.