在c#中将时间戳字符串转换为DateTime对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16103186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:01:15  来源:igfitidea点击:

Convert timestamp string to DateTime object in c#

c#datetimewindows-phone-8

提问by PutraKg

I have timestamp strings in the following format 5/1/2012 3:38:27 PM. How do I convert it to a DateTime object in c#

我有以下格式的时间戳字符串5/1/2012 3:38:27 PM。如何将其转换为 C# 中的 DateTime 对象

采纳答案by MarcinJuraszek

You input string looks like in en-usformat, which is M/d/yyyy h/mm/ss tt. You have to use proper CultureInfoinstance while parsing:

您输入的字符串看起来像en-us格式,即M/d/yyyy h/mm/ss tt. 您必须CultureInfo在解析时使用正确的实例:

var ci = System.Globalization.CultureInfo.GetCultureInfo("en-us");

var value = DateTime.Parse("5/1/2012 3:38:27 PM", ci);

or

或者

var ci = new System.Globalization.CultureInfo("en-us");

回答by Hossein Narimani Rad

Try the DateTime.ParseExactmethod

尝试DateTime.ParseExact方法

回答by Eren Ers?nmez

var date = DateTime.ParseExact("5/1/2012 3:38:27 PM", 
    "M/d/yyyy h:mm:ss tt",
    CultureInfo.InvariantCulture);

回答by Soner G?nül

Try to use DateTime.ParseExactmethod like;

尝试使用DateTime.ParseExact类似的方法;

string s = "5/1/2012 3:38:27 PM";
DateTime date = DateTime.ParseExact(s, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine(date);

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

使用指定的格式和特定​​于区域性的格式信息将日期和时间的指定字符串表示形式转换为其等效的 DateTime。字符串表示的格式必须与指定的格式完全匹配。

Output will be;

输出将是;

01.05.2012 15:38:27

Be aware, this output can change based which Culture you used. Since my Cultureis tr-TR, the date operator is .our culture.

请注意,此输出可能会根据您使用的文化而改变。由于 myCultureistr-TR,日期运算符是.我们的文化。

Here is a DEMO.

这是一个DEMO.

回答by bema

http://www.codeproject.com/Articles/14743/Easy-String-to-DateTime-DateTime-to-String-and-For
this maybe helps you. There you can find a detailled explanation of the ParseExact parameters.

http://www.codeproject.com/Articles/14743/Easy-String-to-DateTime-DateTime-to-String-and-For
这可能对你有帮助。在那里您可以找到 ParseExact 参数的详细说明。