简体   繁体   English

使用基于 TimeZone 的 DateTime.ToString() 格式化日期

[英]Format date using DateTime.ToString() based on TimeZone

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.我阅读了以下问题在 c# 中的特定时区中创建日期时间,并且能够使用时区信息创建日期时间。 But I need to convert the DateTime to string value based on TimeZone.但我需要将 DateTime 转换为基于 TimeZone 的字符串值。

Eg 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 .例如,我将时区设置为印度标准时间并创建了一个日期时间,当我尝试使用ToString()而不是13/12/2019 4:00:00 PM转换为字符串13/12/2019 4:00:00 PM ,我得到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 .由于我已将时区设置为印度标准时间,因此我想以印度格式(dd/mm/yyyy)而不是mm/dd/yyyy显示日期。

So, how do I format the date based on TimeZone in C#?那么,如何在 C# 中根据 TimeZone 格式化日期?

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.但是我需要格式化 DateTime 以匹配用户的地理位置,我可以使用他作为输入提供的时区来识别该地理位置。

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.如果您只需要与特定区域性匹配的DateTime的字符串表示形式,您可以使用DateTime.ToString(IFormatProvider)重载来指定要使用的目标区域性。 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:您还可以使用自定义格式格式化DateTime

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

References:参考:
- DateTime.ToString(IFormatProvider) - DateTime.ToString(IFormatProvider)
- DateTime.ToString(string) - DateTime.ToString(string)
- CultureInfo - 文化资讯
- Date and time formatting - 日期和时间格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM