bill
bill

Reputation: 864

How to remove two characters and replace from a string in the middle in c#

I have a string like this 25/05/2016 now I want to get a string like this 25/05/16 and like this 25-05-2016 how can I do this in c#.

Upvotes: 3

Views: 233

Answers (4)

bill
bill

Reputation: 864

this is what I did

 string s = "25/05/2016";

 var date = DateTime.ParseExact(s, "dd/MM/yyyy",null);
 var date1 = date.ToString("dd/MM/yy");
 var date2 = date.ToString("dd-MM-yyyy");

helped log @Nitin's answer and this stackoverflow questiong

Upvotes: 0

Enigmativity
Enigmativity

Reputation: 117037

You could always just use string manipulation:

var source = "25/05/2016";
var result1 = String.Join("/", source.Split('/').Select(x => x.Substring(x.Length - 2, 2)));
var result2 = source.Replace("/", "-");

These give the correct results:

25/05/16
25-05-2016

Upvotes: 0

Chakratos
Chakratos

Reputation: 49

Nitin's answer is the best for your problem.

But if it were not an date you could convert the String to an byte array, modify the characters you need to and then convert it back to string.

Upvotes: 0

Nitin Purohit
Nitin Purohit

Reputation: 18580

Instead of string manipulation, parse the Date properly:

var date = DateTime.Parse("25/05/2016");

var date1 = date.ToString("dd/MM/yy");   <-- 25/05/16
var date2 = date.ToString("dd-MM-yyyy"); <-- 25-05-2016

Upvotes: 16

Related Questions