如何从给定字符串中提取日期? [英] How to extract date from given string?

查看:108
本文介绍了如何从给定字符串中提取日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从以下给定字符串中提取日期????



2015-06-01t00:00:00



感谢Adavance

How Extract date from following given string????

"2015-06-01t00:00:00"

Thanks in Adavance

推荐答案

一种方法是使用DateTime.TryParse,然后使用Date属性。考虑以下

One way is to use DateTime.TryParse and then the Date property. Consider the following
System.DateTime a;
if(System.DateTime.TryParse("2015-06-01t00:00:00", out a))
{
   System.Diagnostics.Debug.Print(a.Date.ToString());
}



但是,DateTime总是包含时间部分,所以它取决于代码的使用与否。



在实际情况中,只需记住通过调查布尔返回值来检查TryParse是否有效。请参阅 DateTime.TryParse [ ^ ]


我更喜欢使用DateTime.TryParseExact来帮助确保从未转换月份和日期,因为本地开发环境中的区域设置与代码最终可能运行的环境中的区域设置之间存在意外差异(例如,远程Web服务器) )。



如果输入字符串始终遵循相同的模式(例如yyyy-MM-DDtHH:mm:ss),那么我的首选解决方案如下所示: br $> b $ b

I prefer using DateTime.TryParseExact to help ensure the month and day are never transposed due to an unexpected difference between regional settings in my local development environment and regional settings in the environment where the code might eventually run (e.g. a remote web server).

If the input string always follows the same pattern (e.g. "yyyy-MM-DDtHH:mm:ss") then my preferred solution looks like this:

var culture = new CultureInfo("en-US");
var input = "2015-06-01t00:00:00";
DateTime parsed;
if ( DateTime.TryParseExact(input, @"yyyy-MM-dd\tHH:mm:ss", culture, DateTimeStyles.None, out parsed ) )
{
  // parsed.Date contains the date part of the input string
}
else
{
  // Handle the unexpected format
}


这篇关于如何从给定字符串中提取日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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