0

I read the following question Creating a DateTime in a specific Time Zone in c# and was able to create a DateTime with TimeZone information. But I need to convert the DateTime to string value based on TimeZone.

E.g. I've set the TimeZone as India Standard Time and created a DateTime, when I tried to convert to string using ToString() instead of 13/12/2019 4:00:00 PM, I am getting 12/13/2019 4:00:00 PM. Since I've set the TimeZone as India Standard Time, I would like to display the date in India Format (dd/mm/yyyy) rather than mm/dd/yyyy.

So, how do I format the date based on TimeZone in C#?

Edit: I completely understand that Format and Timezone are different things. But I need to format the DateTime to match user's geography which I can identify using his timezone provided as input.

Gopi
  • 5,656
  • 22
  • 80
  • 146
  • Timezone is timezone. Culture dictates how date/time values are formatted. – ProgrammingLlama Dec 11 '19 at 04:44
  • What is your `CurrentCulture` exactly? And can you please show the [MCVE] that demonstrates your problem? – Soner Gönül Dec 11 '19 at 06:39
  • @SonerGönül Irrespective of current culture, I need to change DateTime format as per user's input. TimeZone will be the input from user. – Gopi Dec 11 '19 at 06:52
  • 1
    I think you'll basically need to create a mapping from time zone ID to culture, then use that culture's format. But it's entirely possible that there are some time zones that span multiple cultures, precisely because they're different concepts. I think it would be a lot better to capture the user's culture separately. – Jon Skeet Dec 11 '19 at 07:13
  • There are many cultures in a single timezone, that's why (datetime) format is culture (not timezone) based – Dmitry Bychenko Dec 11 '19 at 07:18

1 Answers1

0

If you only want a string representation of the DateTime that matches a specific culture you can use the DateTime.ToString(IFormatProvider) overload to specify the target culture you want to use. The date will be formatted accordingly. If you want to format your date and time you want to do this based on the culture of the user and not based on the timezone. People in Kongo and Germany share the same timezone but are formatting their date and time differently.

var myDate = DateTime.Now();
var myDateString = myDate.ToString(new CultureInfo("fr-FR"));

would print the date and time in a french format for example.

You can also format your DateTime with a custom format:

var myDate = DateTime.Now;
var myDateString = myDate.ToString("dd/MM/yyyy hh:mm");

References:
- DateTime.ToString(IFormatProvider)
- DateTime.ToString(string)
- CultureInfo
- Date and time formatting

Christian Klemm
  • 1,455
  • 5
  • 28
  • 49