本文介绍了如何在C#中将字符串转换为日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个像下面的字符串,我正在转换为日期时间格式。我尝试过以下方式。有没有其他方法可以做到这一点。格式化后字符串的预期结果应该像yyyy-MM-dd hh:mm:ss ms。 我尝试了什么: StringBuilder myStringBuilder = new StringBuilder(20180215031530000); myStringBuilder = myStringBuilder.Insert(4, - ); myStringBuilder = myStringBuilder.Insert(7, - ); myStringBuilder = myStringBuilder.Insert(10,); myStringBuilder = myStringBuilder。插入(13,:); myStringBuilder = myStringBuilder.Insert(16,:); myStringBuilder = myStringBuilder.Insert(19,。) ; DateTime dt = Convert.ToDateTime(myStringBuilder.ToString());Hi,I have a string like below which is I am converting to datetime format. I tried in below way. Is there any other way to do it. Expected outcome of string after formatting should be like yyyy-MM-dd hh:mm:ss ms.What I have tried:StringBuilder myStringBuilder = new StringBuilder("20180215031530000"); myStringBuilder = myStringBuilder.Insert(4, "-"); myStringBuilder = myStringBuilder.Insert(7, "-"); myStringBuilder = myStringBuilder.Insert(10, " "); myStringBuilder = myStringBuilder.Insert(13, ":"); myStringBuilder = myStringBuilder.Insert(16, ":"); myStringBuilder = myStringBuilder.Insert(19, "."); DateTime dt = Convert.ToDateTime(myStringBuilder.ToString());推荐答案参见DateTime.TryParse Method(System)| Microsoft Docs [ ^ ]以获得更好的方法。See DateTime.TryParse Method (System) | Microsoft Docs[^] for a better method.除了解决方案1的具体示例:In addition to solution 1 a concrete example:var originalTimeString = "20180215031530000";DateTime dt;var success = DateTime.TryParseExact(originalTimeString, "yyyyMMddhhmmssfff", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);if (success){ var newTimeString = dt.ToString("yyyy-MM-dd hh:mm:ss fff");} 尽管如此,请阅读建议的文档。Nevertheless please read the suggested documentation.不要这样做。 使用 DateTime.TryParseExact [ ^ ]而不是插入分隔符:Don't do that.Use DateTime.TryParseExact[^] instead of inserting delimiters:string input = "20180215031530000";DateTime dt;if (!DateTime.TryParseExact(input, "yyyyMMddHHmmssfff", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { Console.WriteLine("Problem with input date"); return; }Console.WriteLine(dt); 这篇关于如何在C#中将字符串转换为日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 06-10 06:35