简体   繁体   English

将字符串转换为12小时格式的日期时间格式

[英]Convert a string to datetime format with 12 hour format

I am having a field type DateTime in SQL server database. 我在SQL Server数据库中有一个字段类型DateTime。 I am developing a webservice to fetch date and time. 我正在开发一个Web服务来获取日期和时间。

The date is stored in this format 4/14/2013 10:10:01 PM in database. 日期以4/14/2013 10:10:01 PM格式存储在数据库中。

Now, I have a webmethod as below: 现在,我有一个webmethod如下:

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. 但是这段代码给了我一个错误,String没有被识别为有效的DateTime。 how can I convert string into datetime format like 4/14/2013 10:10:01 PM?? 如何将字符串转换为日期时间格式,如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 你想要12小时的时钟使用小......你想要24小时制时钟使用大写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. 如果要使用12小时制,请在格式字符串中使用tt以生成AM / PM指示符。

In your format string use tt for PM/AM part. 在您的格式字符串中使用tt表示PM / AM部分。 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 或者这取决于您在last_updated列上的SQL数据类型

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM