使用基于TimeZone的DateTime

使用基于TimeZone的DateTime

本文介绍了使用基于TimeZone的DateTime.ToString()格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如当我尝试使用 ToString()而不是 13/12/2019 4:00:00 PM ,我正在 12/13/2019 4:00:00 PM .由于已将TimeZone设置为印度标准时间,因此我想以印度格式(dd/mm/yyyy)而不是 mm/dd/yyyy 显示日期

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.

那么,如何在C#中基于TimeZone格式化日期?

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

编辑:我完全理解格式和时区是不同的.但是我需要格式化DateTime以匹配用户的地理位置,我可以使用提供的时区作为输入来识别该地理位置.

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 的字符串表示形式,则可以使用 DateTime.ToString(IFormatProvider)重载以指定要使用的目标区域性.日期将被相应地格式化.如果要格式化日期和时间,则要根据用户的习惯而不是时区来进行格式化.孔戈和德国的人共享相同的时区,但日期和时间的格式不同.

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.

您还可以使用自定义格式设置 DateTime 的格式:

You can also format your DateTime with a custom format:

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

参考文献:
- DateTime.ToString(IFormatProvider)
- DateTime.ToString(string)
- CultureInfo
-日期和时间格式

这篇关于使用基于TimeZone的DateTime.ToString()格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 01:04