Lucas Juan
Lucas Juan

Reputation: 371

Get the specific value only from a string to display in textbox C#

The string contains this value:

3/14/1952 12:00:00 AM

Now I want to show only in text box the date not the time how can I do this?

3/14/1952

Upvotes: 0

Views: 510

Answers (4)

Raging Bull
Raging Bull

Reputation: 18737

Try this:

Since you are using space for splitting, you don't have to specify the space character.

string MyString ="3/14/1952 12:00:00 AM";
string date=MyString.Split()[0];

OR

string date=MyString.Split().First();

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98740

I think most secure way is to parsing it to DateTime with DateTime.ParseExact method and using "d" standard date and time format .

As an example;

string s = "3/14/1952 12:00:00 AM";
DateTime dt = DateTime.ParseExact(s,
                                  "M/dd/yyyy HH:mm:ss tt",
                                  CultureInfo.InvariantCulture);
Console.WriteLine(dt.ToString("d"));

Output will be;

3/14/1952

Here a demonstration.

After parsing process, you can use this value in your TextBox with .Text property like;

TextBox1.Text = dt.ToString("d");

Upvotes: 3

Chris Shao
Chris Shao

Reputation: 8231

There are 2 solutions:
1. parse it to datetime and then convert it to your string format

var dateTime = DateTime.Parse("3/14/1952 12:00:00 AM");
var yourString = datetime.ToString("M/dd/yyyy");

2. just split it by string.Split method

string yourString = str.Split(' ')[0];

Upvotes: 1

Adil
Adil

Reputation: 148110

You can use string.Split that will give you array of strings and your required date string is at zero index.

string date = str.Split(' ')[0];

Upvotes: 2

Related Questions