Split date in c #
4 answers
To analyze / validate the three expected formats, you can use something like below. Given the template, once you know what it really is, you can simply use string.Split
to get the first part; if you need something more elegant, you can use TryParseExact
for each template in turn and extract the part you want (or reformat it).
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);
+5
a source to share
Use DateTime.Parse (String, IFormatProvider) or DateTime.ParseExact to convert the string to DateTime.
Then you can extract the day, month and year using the corresponding properties .
+1
a source to share
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 backtrack trying to parse it using a different culture.
Edit: Added M
0
a source to share