如何在C#中仅从字符串中选择日期 [英] How to select only date from string in C#

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

问题描述

你好我有一个字符串我的应用程序是我从数据库中检索我只想从我的字符串中选择日期



我有什么尝试过:



我的字符串是字符串var = P 2016-10-31;我试过这个但是我能从这里得到的只有我能做什么才能这样才能选择日期(2016-10-31)

解决方案

< pre lang =C#> string myString = P 2016年10月31\" 日;
string [] parts = mystring.Split(' ');
DateTime date = DateTime.ParseExact(parts [ 1 ], yyyy-MM-dd,CultureInfo.InvariantCulture);


这实际上取决于数据的格式 - 如果它总是一个字符,一个空格,然后是日期,它是微不足道的:

  string  input =   P 2016-10-31; 
string justTheDate = input.Substring( 2 );
DateTime dt;
if (DateTime.TryParseExact(justTheDate, yyyy-M-dd,CultureInfo.InvariantCulture,DateTimeStyles.None, out dt))
{
...
}



如果它有所不同,那么你需要仔细查看 可以 的确切内容而是考虑使用正则表达式。


  string  s =   P 2016-10-31; 
DateTime dt;
DateTime.TryParseExact(s, P yyyy-MM-dd,System.Globalization .CultureInfo.CurrentCulture,System.Globalization.DateTimeStyles.None, out dt);


hello i have a string i my application which is i am retrieving from database i want to only select the date from my string

What I have tried:

my string is string var = P 2016-10-31; i have tried this but i can able get only P from this what can i do so i can able to select only date (2016-10-31)

解决方案

string myString = "P 2016-10-31";
string[] parts = mystring.Split(' ');
DateTime date = DateTime.ParseExact(parts[1], "yyyy-MM-dd", CultureInfo.InvariantCulture);


It really depends on the format of the data - if it's always a single char, a space, and then the date, it's trivial:

string input = "P 2016-10-31";
string justTheDate = input.Substring(2);
DateTime dt;
if (DateTime.TryParseExact(justTheDate, "yyyy-M-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
    {
    ...
    }


If it varies, then you need to look closely at exactly what it can be and maybe consider a Regex instead.


string s = "P 2016-10-31";
DateTime dt;
DateTime.TryParseExact(s, "P yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dt);


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

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