C# to Convert String to DateTime

前端 未结 6 1897
北海茫月
北海茫月 2020-12-21 11:59

How to convert the below string to DateTime in C#?

Mon Apr 22 07:56:21 +0000 2013

When i tried the code with

         


        
相关标签:
6条回答
  • 2020-12-21 12:40

    Use DateTime.ParseExact like:

    string str = "Mon Apr 22 07:56:21 +0000 2013";
    DateTime dt = DateTime.ParseExact(str,
                                       "ffffd MMM d HH:mm:ss +0000 yyyy",
                                       CultureInfo.InvariantCulture);
    
    0 讨论(0)
  • 2020-12-21 12:40
    string input = "Mon Apr 22 07:56:21 +0000 2013";
    string format = "ffffd MMM dd HH:mm:ss +ffff yyyy";
    DateTime dt;
    if(DateTime.TryParseExact(input,format,  CultureInfo.InvariantCulture,
                DateTimeStyles.None,out dt))
    {
        // do something with dt
    }
    
    0 讨论(0)
  • 2020-12-21 12:40

    You can use this:

    using System;
    using System.Globalization;
    
    namespace ConsoleApplication3
    {
        class Program
        {
            static void Main(string[] args)
            {
                CultureInfo cult = CultureInfo.InvariantCulture;
    
                string txt = "Mon Apr 22 07:56:21 +0000 2013";
                string format = "ffffd MMM dd hh:mm:ss zzz yyyy";
                DateTime dt = DateTime.ParseExact(txt, format, cult);
    
            }
        }
    }
    

    If you run program from country with +06:00, you get time 13:56:21 with same date

    0 讨论(0)
  • 2020-12-21 12:42

    You have to specify that your input string is in a particular format. Please refer this link and this one too.

    0 讨论(0)
  • 2020-12-21 12:44

    Try DateTime.ParseExact instead.

    Example:

    CultureInfo provider = CultureInfo.InvariantCulture;
    dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
    format = "ffffd dd MMM yyyy h:mm tt zzz";
    result = DateTime.ParseExact(dateString, format, provider);
    

    More examples are available at http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

    0 讨论(0)
  • 2020-12-21 12:53

    You have basically two options for this. DateTime.Parse() and DateTime.ParseExact(). like

    DateTime parseexactdt = DateTime.ParseExact("Mon Apr 22 07:56:21 +0000 2013",
                                       "ffffd MMM d HH:mm:ss +0000 yyyy",
                                       CultureInfo.InvariantCulture);
    
    0 讨论(0)
提交回复
热议问题