Convert a string to datetime format with 12 hour format

26,391

Solution 1

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  + "')";

Solution 2

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.

Solution 3

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?

Share:
26,391
Khushbu
Author by

Khushbu

Updated on July 22, 2022

Comments

  • Khushbu
    Khushbu almost 2 years

    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!