2012-12-15 140 views
2

可能重复:
Date time format from string?将字符串转换为DateTime

有谁知道我怎么能下列字符串转换为C#中的DateTime价值?

"Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)" 
+0

也期待http://stackoverflow.com/questions/919244/converting-string- to-datetime-c-net –

+0

@Bhushan Firake。我已经尝试过DateTime.ParseExact(字符串,格式,格式提供程序),但是我应该使用什么格式以上 – lafama

+1

@lafama:您可以阅读本文http://www.codeproject.com/Articles/14743/Easy-String日期时间 - 日期时间 - 字符串 - 和 - 对于 –

回答

6

如果你仅仅使用"GMT+0300 (E. Africa Standard Time)"结尾的字符串,你可以尝试:是

string dateString = "Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)"; 
DateTime date = DateTime.ParseExact(dateString, "ddd MMM dd yyyy HH:mm:ss 'GMT+0300 (E. Africa Standard Time)'", System.Globalization.CultureInfo.InvariantCulture); 

的说明符的含义如下:

  • “ddd”缩写名称o星期几。
  • “MMM”月份的缩写名称。
  • “dd”月的日期,从01到31.
  • “yyyy”年份为四位数字。
  • “HH”的小时,通过59
  • 使用从00 24小时时钟从00到59
  • “SS”的第二个,从00到23
  • “毫米”的那一刻, “
  • ”:“时间分隔符。
  • “string”,“string”文字字符串分隔符。

你可以找到更多关于命名Custom Date and Time Format Strings

而且,如果你想太多解析"GMT+0300 (E. Africa Standard Time)"部分MSDN文章在不同的格式说明,我想你应该执行的方式给自己解析。我不认为这是一个说明者。

+1

原则上你的指定符列表还应该提及:?'':''你使用的格式提供者的'TimeSeparator';将转化为不变文化的':'。翻译成其他文化的“。”。 –

+0

@杰普:你说得对,我忘了那个。现在添加它。 – hattenn

0

试试这个:

DateTime date = DateTime.Parse(yourDateTimeString); 
+0

对不起。这是行不通的 – lafama

1

首先,你应该为你的非洲标准时间文化信息使用';

CultureInfo("af-ZA", false); 

但是你的字符串转换为DateTime真的很复杂。对我来说,看起来不可能完美转换为DateTime。但我们可以在你的弦乐中进行一些修复。例如,如果你的字符串是这样的; "11/15/2012 00:00:00"你可以像这样转换它;

using System; 
using System.Globalization; 

namespace Programs 
{ 
    public class Program 
    {  
     public static void Main(string[] args) 
     { 
      string str = "11/15/2012 00:00:00"; 
      DateTime dt = DateTime.ParseExact(str, "MM/dd/yyyy hh:mm:ss", new CultureInfo("af-ZA")); 
      Console.WriteLine(dt.ToString()); 
     } 
    } 
} 

Custom Date and Time Format Strings

​​

0

有没有办法来处理(E.非洲标准时间)。

假设UTC = GMT还可以得到时区的一部分,只是删除不是你的字符串的重要组成部分

string t = Regex.Replace("Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)", "([(].+?[)])", ""); 
t= t.Replace("GMT", "").Trim(); 

DateTime a = DateTime.ParseExact(t, "ddd MMM dd yyyy HH:mm:ss zzzz", System.Globalization.CultureInfo.InvariantCulture);