C# to Convert String to DateTime

2020-02-14 10:39发布

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

Mon Apr 22 07:56:21 +0000 2013

When i tried the code with

Convert.ToDateTime("Mon Apr 22 07:56:21 +0000 2013")

it is throwing error as

String was not considered as valid DateTime

标签: c#
6条回答
老娘就宠你
2楼-- · 2020-02-14 11:08

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",
                                   "ddd MMM d HH:mm:ss +0000 yyyy",
                                   CultureInfo.InvariantCulture);
查看更多
姐就是有狂的资本
3楼-- · 2020-02-14 11:21
string input = "Mon Apr 22 07:56:21 +0000 2013";
string format = "ddd MMM dd HH:mm:ss +ffff yyyy";
DateTime dt;
if(DateTime.TryParseExact(input,format,  CultureInfo.InvariantCulture,
            DateTimeStyles.None,out dt))
{
    // do something with dt
}
查看更多
Summer. ? 凉城
4楼-- · 2020-02-14 11:24

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 = "ddd 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

查看更多
ゆ 、 Hurt°
5楼-- · 2020-02-14 11:25

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

查看更多
地球回转人心会变
6楼-- · 2020-02-14 11:30

Use DateTime.ParseExact like:

string str = "Mon Apr 22 07:56:21 +0000 2013";
DateTime dt = DateTime.ParseExact(str,
                                   "ddd MMM d HH:mm:ss +0000 yyyy",
                                   CultureInfo.InvariantCulture);
查看更多
We Are One
7楼-- · 2020-02-14 11:32

Try DateTime.ParseExact instead.

Example:

CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd 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

查看更多
登录 后发表回答