简体   繁体   English

将各种日期时间格式转换为特定的格式

[英]Convert various datetime formats to an specific one

I'm developing an application where I get various datetime formats from users (like 27/02/2016 12:00:00 AM , 02/28/16 12:00:00 AM , 4/18/2016 00:00:00 ,...) and I have to convert all to M/dd/yyyy h:mm:ss .我正在开发一个应用程序,我从用户那里获取各种日期时间格式(例如27/02/2016 12:00:00 AM02/28/16 12:00:00 AM4/18/2016 00:00:00 ,...) 并且我必须全部转换为M/dd/yyyy h:mm:ss

I tried:我试过:

DateTime.ParseExact(dateText,"M/d/yyyy HH:mm:ss", null);
DateTime.ParseExact(dateText,"M/d/yyyy h:mm:ss tt", null);

I also replaced null by CultureInfo.InvariantCulture , CultureInfo.CurrentUICulture.DateTimeFormat and CultureInfo.CurrentCulture which mentioned in many questions about converting string to datetime.我还用CultureInfo.InvariantCultureCultureInfo.CurrentUICulture.DateTimeFormatCultureInfo.CurrentCulture替换了null ,它们在许多关于将字符串转换为日期时间的问题中提到。

But I always get:但我总是得到:

String was not recognized as a valid DateTime字符串未被识别为有效的日期时间

I can convert 27/02/2016 12:00:00 AM if I code like this:如果我这样编码,我可以转换27/02/2016 12:00:00 AM

DateTime.ParseExact(dateText,"d/M/yyyy hh:mm:ss tt", null);

But that's not what I want.但这不是我想要的。

Is there anyway to convert any datetime format to M/dd/yyyy HH:mm:ss using one line code or at least a method?无论如何,是否可以使用一行代码或至少一种方法将任何日期时间格式转换为M/dd/yyyy HH:mm:ss

If you know what all the possible formats are then you should call the overload of DateTime.TryParseExact that takes an array of allowable formats.如果您知道所有可能的格式是什么,那么您应该调用DateTime.TryParseExact的重载,它采用一组允许的格式。 Otherwise, you should probably call DateTime.TryParse , which will test all possible standard formats for the current culture.否则,您可能应该调用DateTime.TryParse ,它将测试当前文化的所有可能的标准格式。

If you know for a fact that the text is valid then you can use ParseExact or Parse instead and then call ToString directly on the result.如果您知道文本有效,那么您可以改用ParseExactParse ,然后直接对结果调用ToString If you do use one of the Try methods then you'll first have to test whether the conversion was successful and, if it is was, then you can call ToString on the result.如果您确实使用了Try方法之一,那么您首先必须测试转换是否成功,如果成功,则可以对结果调用ToString

You can convert it like this :你可以像这样转换它:

string text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff",
                                CultureInfo.InvariantCulture);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM