0

I have following string stored in datatable's column with varchar or string datatype "4/29/2013 9:00:00 PM"

Now i want to convert this string to datetime

Or let me make more clear I just want to extract time part from this string "4/29/2013 9:00:00 PM" and store it in Database. Please help me. Thanks in advance

4

6 Answers 6

4
 // String to DateTime
 String MyString;
 MyString = "4/29/2013 9:00:00 PM";

 DateTime MyDateTime;
 MyDateTime = new DateTime();
 MyDateTime = DateTime.ParseExact(MyString, "M/dd/yyyy hh:mm:ss tt",
                                  null);

this should work for you.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 becuase this answer does not make UASA based assumptions about the local of the database or the code accessing it.
Almost right - you really should have "MM/dd/yyyy hh:mm:ss tt" as the month may be two digits.
+1 for giving the format because many times date parsing is a pain in the ass. If we know the format prior, it's better to give it. In the writing part also this has to be take care.
1

Ok so this is a fairly simple operation you can use DateTime date = DateTime.Parse(dbString) and then use date.ToString("hh:mm tt") To get just the time and AM/PM. in the form "09:00 PM"

'hh' stands for the hours 01 to 12,

'mm' stands for the minutes 00 to 59,

'tt' stands for AM/PM

You could also use date.ToString("h:mm tt") to get the form "9:00 PM".

Comments

0
DateTime yourDateTime = DateTime.ParseExact(dateString, "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);

Comments

0

Try this :

    string myDateTimeString = "4/29/2013 9:00:00 PM";
    DateTime myDateTime = DateTime.Parse(myDateTimeString);
    string myTimeString = myDateTime.Date.ToString("hh:mm tt");

Hope this helps!

Comments

0

Time part of string in SQL :

select  DATEPART(HOUR , cast('4/29/2013 9:00:00 PM' as datetime) ) as hr
      , DATEPART(MINUTE , cast('4/29/2013 9:00:00 PM' as datetime) ) as minute
      , DATEPART(SECOND , cast('4/29/2013 9:00:00 PM' as datetime) ) as sec

1 Comment

@lelyor - Actually he did.
0

Or try this ext:

public static class Ext
{

    public static string AsLocaleDateString(this DateTime dt)
    {
        var format = Thread.CurrentThread.CurrentUICulture.DateTimeFormat;

        return dt.ToString(format.ShortDatePattern);
    }

    public static DateTime? AsLocaleDate(this string str)
    {
        if (str.IsNullEmpty())
        {
            return null;
        }
        var format = Thread.CurrentThread.CurrentUICulture.DateTimeFormat;

        return DateTime.ParseExact(str, format.ShortDatePattern, CultureInfo.InvariantCulture, DateTimeStyles.None);
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.