解析字符串,日期时间在C# [英] Parse string to DateTime in C#

查看:191
本文介绍了解析字符串,日期时间在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的日期和时间的格式一样,一个字符串:

I have date and time in a string formatted like that one:

"2011-03-21 13:26" //year-month-day hour:minute

我如何可以解析为的System.DateTime

我想使用像 DateTime.Parse函数() DateTime.ParseExact()如果有可能,能够手动指定日期的格式。

I want to use functions like DateTime.Parse() or DateTime.ParseExact() if possible, to be able to specify the format of the date manually.

推荐答案

DateTime.Parse()将尝试找出给定日期的格式,它通常不会一份好工作。如果你能保证日期将永远是在一个给定的格式,那么你可以使用 ParseExact()

DateTime.Parse() will try figure out the format of the given date, and it usually does a good job. If you can guarantee dates will always be in a given format then you can use ParseExact():

string s = "2011-03-21 13:26";

DateTime dt = 
    DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

(但请注意,它通常是使用更安全的方法的TryParse万一一个日期不在预期的格式1)

(But note that it is usually safer to use one of the TryParse methods in case a date is not in the expected format)

请一定要检查自定义日期和时间格式字符串的构建格式字符串时,尤其要注意字母和数字的情况下(即MM和MM的意思是非常不同的东西)。

Make sure to check Custom Date and Time Format Strings when constructing format string, especially pay attention to number of letters and case (i.e. "MM" and "mm" mean very different things).

对于C#格式化字符串另一个有用的资源是字符串格式化C#中

Another useful resource for C# format strings is String Formatting in C#

这篇关于解析字符串,日期时间在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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