3

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#.

bill
  • 854
  • 3
  • 17
  • 41

4 Answers4

16

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
Nitin
  • 18,344
  • 2
  • 36
  • 53
0

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.

Chakratos
  • 49
  • 1
  • 10
0

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
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0

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

Community
  • 1
  • 1
bill
  • 854
  • 3
  • 17
  • 41