bachchan
bachchan

Reputation: 313

Split the date in c#

For Ex You date enter in the various form in textbox

  1. 12/Augest/2010
  2. augest/12/2010
  3. 2010/12/Augest

and out put is three textbox First is day show= 12 textbox second is Months show= augest textbox third is Year show= 2010

Upvotes: 2

Views: 11341

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1062630

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; if you need something more elegant you could use TryParseExact for each pattern in turn and extract the desired portion (or re-format 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);

Upvotes: 5

Hans Olsson
Hans Olsson

Reputation: 55009

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.

Edit: Added an M

Upvotes: 0

Amsakanna
Amsakanna

Reputation: 12934

Use DateTime.Parse(String, IFormatProvider) or DateTime.ParseExact to convert the string into DateTime.

Then you can extract the day, month and year using the corresponding properties.

Upvotes: 1

Byron Ross
Byron Ross

Reputation: 1605

Use DateTime.Parse(s). See MSDN

Then you can get the individual parts of a DateTime structure.

e.g.

DateTime date = DateTime.Parse("some input date string");
string day = DateTime.Day.ToString();
string month = DateTime.Month.ToString();
string year = DateTime.Year.ToString();

Upvotes: 0

Related Questions