user2264732
user2264732

Reputation: 31

c# String to DateTime in c#

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

Upvotes: 0

Views: 237

Answers (6)

Elyor
Elyor

Reputation: 865

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

}

Upvotes: 0

Sachin
Sachin

Reputation: 2148

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

Upvotes: 0

bema
bema

Reputation: 395

 // 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.

Upvotes: 4

Obama
Obama

Reputation: 2612

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!

Upvotes: 0

Toon Casteele
Toon Casteele

Reputation: 2579

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

Upvotes: 0

Nomad101
Nomad101

Reputation: 1698

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".

Upvotes: 1

Related Questions