How to convert string to DateTime?

KorlakuntaBabuKorlakuntaBabu USMember ✭✭
edited February 22 in Xamarin.Android

Hi, i am android and Ios developer, i would like to convert string to DateTime

      `string nodeValue = "2013-02-11T14:29:01-05:00";`

The nodeValue comes from after converting DataSet to XMLDocument

how can i get the DateTime value as 2/11/2013 2:29:01 PM?

Help me please...

Best Answer

  • KorlakuntaBabuKorlakuntaBabu US ✭✭
    edited February 22 Accepted Answer

    Finally got solution

     string nodeValue = "2013-02-11T14:29:01-05:00";
    DateTimeOffset dtOffset;
    
    if(DateTimeOffset.TryParse(nodeValue,null,DateTimeStyles.None,out dtOffset))
    {
        DateTime myDate = dtOffset.DateTime;
    
            //output myDate
            //2/11/2013 2:29:01 PM
    }
    

Answers

  • Sumit_SharmaSumit_Sharma USMember ✭✭✭
    edited February 22

    string nodeValue = "2013-02-11T14:29:01-05:00";

    long b = 0;
    var date = DateTime.Parse(nodeValue);
    Console.WriteLine(date.ToString("MM-dd-yyyy hh:mm:ss"));
    

    Result:

    02-12-2013 12:59:01
    
  • KorlakuntaBabuKorlakuntaBabu USMember ✭✭

    Thank you!

                    i tried that,but expected DateTime value is 2/11/2013 2:29:01 PM
    
  • M_Shah04M_Shah04 USMember ✭✭✭
    edited February 22

    You can convert string to date time like this:

    DateTime myDate = DateTime.ParseExact("2013-02-11T14:29:01", "yyyy'-'MM'-'dd'T'HH':'mm':'ss", System.Globalization.CultureInfo.InvariantCulture);
    

    I have used 2013-02-11T14:29:01 instead of 2013-02-11T14:29:01-05:00 and its showing date time as per your requirement.

    You can also refer sortable DateTime pattern here: https://docs.microsoft.com/en-us/dotnet/api/system.globalization.datetimeformatinfo.sortabledatetimepattern?view=netframework-4.7.2
    Hope this may solve your issue.

  • KorlakuntaBabuKorlakuntaBabu USMember ✭✭

    Yes if we use 2013-02-11T14:29:01 instead of 2013-02-11T14:29:01-05:00 Then result was expected one
    Thank you

  • KorlakuntaBabuKorlakuntaBabu USMember ✭✭
    edited February 22 Accepted Answer

    Finally got solution

     string nodeValue = "2013-02-11T14:29:01-05:00";
    DateTimeOffset dtOffset;
    
    if(DateTimeOffset.TryParse(nodeValue,null,DateTimeStyles.None,out dtOffset))
    {
        DateTime myDate = dtOffset.DateTime;
    
            //output myDate
            //2/11/2013 2:29:01 PM
    }
    
Sign In or Register to comment.