将未知格式的字符串转换为c#中的日期 [英] convert string in unknown format to date in c#

查看:117
本文介绍了将未知格式的字符串转换为c#中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在stackoverflow上搜索了答案,但是没有运气。我正在开发Windows应用程序,并且有一些日期格式不同的字符串,例如

I have searched stackoverflow for an answer but no luck. I am developing a windows application and I have some strings in different date formats, eg.

dd/MM/yyyy
MM/dd/yyyy
MM-dd-yyyy
dd-MM-yyyy
dd/MM/yyyy hh:mm::ss
MM/dd/yyyy hh:mm::ss
etc...

但是我需要转换转换为通用格式- dd / MM / yyyy 。该应用程序可以在具有不同文化背景的任何Windows计算机上运行。

But I need to convert in to a common format - dd/MM/yyyy. The application can run in any windows machines in different culture.

正确的方法是什么?

编辑:还有一件事,我可能不知道传入字符串的格式。

One more thing I may not know what the format of incoming string.

预先感谢。

推荐答案

使用 DateTime.ParseExact 具有不同的格式格式。

Use DateTime.ParseExact with the different patterns as formats.

如果在解析后您确实需要使用字符串表示形式,请使用 ToString < DateTime 的/ code>方法具有您感兴趣的显式格式(因此它是区域性的)。但是最好保留 DateTime ,因为这与格式无关。

If after parsing you really need to use a string representation, use the ToString method of the DateTime with the explicit format that you're interested in (so that it is culture-invariant). It's better however to keep the DateTime because this is format-agnostic.

这篇关于将未知格式的字符串转换为c#中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆