7

I want to have date as 02/03/2017 for 3 March 2017 in my mvc view.

With DateTime.ToString("dd/MM/yyyy") I just get 02 03 2017. Why is my slashes going away?

rethabile
  • 3,029
  • 6
  • 34
  • 68
  • 1
    No repro: http://ideone.com/7gioH2. – Patrick Hofman Mar 02 '17 at 09:51
  • 1
    You can try `ToString(@"dd/MM/yyyy");` – Mohit S Mar 02 '17 at 09:52
  • 5
    Slash in date time format represents culture-specific delimiter. For en culture that is still slash, but for russian culture for example it is dot ("."). For culture you use it seems to be a space. So if you want culture-specific format - better not escape slashes but pass appopriate culture to ToString method. – Evk Mar 02 '17 at 09:52
  • 1
    The slashes have a special meaning when it comes to parsing dates. It will be replaced with your current culture's date-separator. To avoid this you have to escape them like Dmitry has already shown or use `InvariantCulture` as second argument. You can read about it [here](https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx#The) at _"The "/" custom format specifier"_ – Tim Schmelter Mar 02 '17 at 09:53
  • What culture do you want to display the date in? – Matthew Watson Mar 02 '17 at 09:54

2 Answers2

18

You might need to provide a culture for your to string.

DateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Stralos
  • 4,895
  • 4
  • 22
  • 40
  • this seems to do the trick. what does the `CultureInfo.InvariantCulture` tell the method to do? What would happen if i run it in Russia as others have put forward as an example? – rethabile Mar 02 '17 at 10:08
  • I think this posts sums up what it up: http://stackoverflow.com/a/9760339/3410616 if you do not provide the Culture property your application uses the default culture you have set on your computer or main application thread. I hope I got the question right(in the comment). If I got your question right, you can mark my answer. p.s. If you don't want to set the culture everytime, set the culture of your main thread (tho you will need to google how to do it. It's easy tho). – Stralos Mar 02 '17 at 11:11
4

Escape slashes:

 var result = MyDateTime.ToString("dd'/'MM'/'yyyy");
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 2
    Actually that's not "escaping" the slashes; that's just specifying a string using the "literal string delimiter". While this works, it may be more natural to use the escape character to actually escape the slashes: `MyDateTime.ToString("dd\\/MM\\/yyyy");` or `MyDateTime.ToString(@"dd\/MM\/yyyy");` - although you might argue this is less readable... ;) – Matthew Watson Mar 02 '17 at 09:57