解析字符串到C#中的DateTime [英] Parse string to DateTime in C#

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

问题描述

我有一个格式如此的字符串日期和时间

 2011- 03-21 13:26//年月日小时:分钟

我如何解析我想使用诸如 DateTime.Parse(...)的函数,它的 System.DateTime



< )
DateTime.ParseExact()如果可能,可以手动指定日期的格式。

解决方案

DateTime.Parse()将尝试找出给定日期的格式,一份好工作。如果您可以保证日期始终为给定格式,则可以使用 ParseExact()

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

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

(但请注意,如果日期不是,请使用TryParse方法之一更安全在预期的格式)



确保检查自定义日期和时间格式字符串,当构建格式字符串时,特别注意字母数和字母数(即MM和mm表示非常不同) 。



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


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

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

How can I parse it to System.DateTime?

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() 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);

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

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).

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

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

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