如何使用C#将此“ 2012-08-16T19:20:30.456 + 08:00”字符串转换为DateTime

时间:2019-09-19 08:49:48

标签: c# datetime-conversion string-to-datetime

我想使用C#将字符串datetime转换为Datetime。我将日期时间存储在sql数据库中

4 个答案:

答案 0 :(得分:3)

示例中的字符串具有偏移量成分,因此您可以使用DateTimeOffset

var dateTimeOffset = DateTimeOffset.Parse("2012-08-16T19:20:30.456+08:00", CultureInfo.InvariantCulture);

从链接的文档中:

  

DateTimeOffset结构包含一个DateTime值,以及   一个Offset属性,用于定义当前   DateTimeOffset实例的日期和时间以及世界标准时间   (UTC)。

答案 1 :(得分:2)

//string value of date
var iDate = "2012-08-16T19:20:30.456+08:00";  

//Convert.ToDateTime(String)
//This method will converts the specified string representation of a date and time to an equivalent date and time value
var dateConversion1 = Convert.ToDateTime(iDate);

//DateTime.Parse()
//DateTime.Parse method supports many formats. It is very forgiving in terms of syntax and will parse dates in many different formats. That means, this method can parse only strings consisting exactly of a date/time presentation, it cannot look for date/time among text.
var dateConversion2 = DateTime.Parse(iDate);

//DateTime.ParseExact()
//ParseExact method will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. The format of the string representation must match the specified format exactly.
var dateConversion3 = DateTime.ParseExact(iDate, "yyyy-MM-dd HH:mm tt", null);

//CultureInfo
//The CultureInfo.InvariantCulture property is neither a neutral nor a specific culture. It is a third type of culture that is culture-insensitive. It is associated with the English language but not with a country or region.
var dateConversion4 = DateTime.ParseExact(iDate, "yyyy-MM-dd HH:mm tt", System.Globalization.CultureInfo.InvariantCulture);

//DateTime.TryParse method
//DateTime.TryParse converts the specified string representation of a date and time to its DateTime equivalent using the specified culture - specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.
DateTime dateConversion5;
DateTime.TryParse(iDate, out dateConversion5);

这些C#方法可以用作DATETIME的转换字符串,请确保该字符串是有效的字符串,以便您进行转换。

答案 2 :(得分:1)

正义

DateTime date= DateTime.Parse(dateString);

答案 3 :(得分:1)

  • 使用DateTime.Parse("2012-08-16T19:20:30.456+08:00")
  • 使用可以使用C#交互式Windows对其进行测试。 enter image description here