[英]Split the date in c#
For Ex You date enter in the various form in textbox 对于Ex You date,在文本框中输入各种形式
and out put is three textbox First is day show= 12 textbox second is Months show= augest textbox third is Year show= 2010 输出是三个文本框,第一个是日显示= 12个文本框,第二个是月显示=最重要的文本框,第三个是年显示= 2010
To parse/validate against three expected formats, you can use something like below. 要针对三种期望的格式进行解析/验证,可以使用类似以下的内容。 Given the pattern, once you know it is valid you could just use
string.Split
to get the first part; 给定模式,一旦知道它是有效的,就可以使用
string.Split
来获得第一部分; if you need something more elegant you could use TryParseExact
for each pattern in turn and extract the desired portion (or re-format it). 如果您需要更精美的东西,可以依次对每个模式使用
TryParseExact
并提取所需的部分(或重新设置其格式)。
string s1 = "12/August/2010",
s2 = "August/12/2010",
s3 = "2010/12/August";
string[] formats = { "dd/MMMM/yyyy", "MMMM/dd/yyyy", "yyyy/dd/MMMM" };
DateTime d1 = DateTime.ParseExact(s1, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None),
d2 = DateTime.ParseExact(s2, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None),
d3 = DateTime.ParseExact(s3, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None);
Use DateTime.Parse(String, IFormatProvider) or DateTime.ParseExact to convert the string into DateTime. 使用DateTime.Parse(String,IFormatProvider)或DateTime.ParseExact将字符串转换为DateTime。
Then you can extract the day, month and year using the corresponding properties . 然后,您可以使用相应的属性提取日,月和年。
date dt date.Parse(txtBox.text);
txtBox1.Text = dt.Day.ToString();
txtBox2.Text = dt.ToString("MMM");
txtBox3.Text = dt.Year.ToString();
date.Parse might throw depending on the string you give it, but then you can fall back by trying to parse it using a different culture. date.Parse可能会根据您提供的字符串而抛出,但是您可以通过尝试使用其他区域性来解析它来回退。
Edit: Added an M 编辑:添加了一个M
Use DateTime.Parse(s)
. 使用
DateTime.Parse(s)
。 See MSDN 参见MSDN
Then you can get the individual parts of a DateTime structure. 然后,您可以获取DateTime结构的各个部分。
eg 例如
DateTime date = DateTime.Parse("some input date string");
string day = DateTime.Day.ToString();
string month = DateTime.Month.ToString();
string year = DateTime.Year.ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.