saltshaker
saltshaker

Reputation:

How to format a Date without using code - Format String Question

How can I achieve the following with a format string: Do 01.01.2009 ? It has to work in all languages (the example would be for Germany). So there should only be the short weekday and then the short date.

I tried 'ddd d' (without the '). However, this leads to 'Do 01'. Is there maybe a character I can put before the 'd' so that it is tread on its own or something like that?

Upvotes: 2

Views: 1926

Answers (6)

Dan Herbert
Dan Herbert

Reputation: 103417

If you want to ensure the same characters are used as separators, you have to use a backslash to escape the character, otherwise it will default to the locale you are in. I recommend using this string if you want the format you specified in your question

DateTime.Now.ToString("ddd dd.MM.yyyy");

To use forward slashes instead, you should escape them so that they always output as slashes.

DateTime.Now.ToString("ddd dd\\/MM\\/yyyy");

Upvotes: 0

Yuval Adam
Yuval Adam

Reputation: 165242

Just for reference, in Java it goes like this:

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
String formattedDate = dateFormat.format(date);

Upvotes: 0

Jared Harley
Jared Harley

Reputation: 8337

If you want to localize (I assume so, since you said "all languages"), you can use CultureInfo to set the different cultures you want to display. The MSDN library has info on Standard Date and Time Format Strings and CultureInfo Class.

The example MSDN provides:

// Display using pt-BR culture's short date format
DateTime thisDate = new DateTime(2008, 3, 15);
CultureInfo culture = new CultureInfo("pt-BR");      
Console.WriteLine(thisDate.ToString("d", culture));  // Displays 15/3/2008

Upvotes: 0

Rowland Shaw
Rowland Shaw

Reputation: 38130

To get the locale specific short date, as well as the locale day name then you're going to have to use two calls, so:

 myDate.ToString("ddd ") + myDate.ToString("d");

Have you considered using the long date format instead?

Upvotes: 0

cowgod
cowgod

Reputation: 8656

You should be using the ISO 8601 standard if you are targeting audiences with varied spoken languages.

DateTime.Now.ToString("ddd yyyy-MM-dd");

Alternatively, you can target the current culture with a short date:

DateTime.Now.ToString("d", Thread.CurrentThread.CurrentCulture);

or a long date:

DateTime.Now.ToString("D", Thread.CurrentThread.CurrentCulture);

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

DateTime.Now.ToString("ddd dd/MM/yyyy")

Upvotes: 3

Related Questions