2

I need to be able to get the current date as string in different formats.

TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var utcNow = DateTime.UtcNow;
var localTime = TimeZoneInfo.ConvertTimeFromUtc(utcNow, timeZone);
Console.WriteLine(localTime.ToShortDateString());

The example above prints the date as 22-01-2018, which is the danish format. But I need it to print the date as 1/22/2018 (example only).

I know that I can format dates using ToString, but I need to be able to format the date from a range of different timezones (the user picks the timezone).

Can I somehow tell ToShortDateString to use another culture and if so, how do I get from TimeZoneInfo to CultureInfo?

ThomasArdal
  • 4,999
  • 4
  • 33
  • 73
  • 1
    You can change the culture of your current thread or of the whole application. See: https://stackoverflow.com/questions/468791/is-there-a-way-of-setting-culture-for-a-whole-application-all-current-threads-a – Thomas Voß Jan 23 '18 at 07:22
  • 1
    @ThomasVoß Why? You can simply give it as parameter to DateTime.ToString(...) without changing _all_ aspects for your thread/app. Yours is better suited if you want to have a world-wide app, thats completely set to one TZ/culture or the other instead of having outputs for different cultures – Patrick Artner Jan 23 '18 at 07:25
  • I'm not sure there is a reliable real-world mapping from Time Zone to preferred date format. [This article](https://msdn.microsoft.com/en-us/library/5hh873ya(v=vs.100).aspx) discusses how to carry out culture-specific formatting, but it may be that it's not possible to infer culture from TZ. – peeebeee Jan 23 '18 at 07:26

1 Answers1

3

You cannot directly convert TimeZoneInfo to CultureInfo unfortunately.

The problem is that in any given timezone there are many countries which fall into it and hence many different culture settings.

The awesome Noda Time by Jon Skeet includes country code -> timezone mappings so you could use that to know which countries are in your given time zone. But from there, you will have to choose the target country somehow.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91