如何在不同的系统文化中转换DateTime? [英] How to convert DateTime in different System culture?

查看:79
本文介绍了如何在不同的系统文化中转换DateTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以不同的区域性格式转换 DateTime 的值,无论系统中设置了什么。

I need to convert DateTime value in different culture format, whatever set in system.

没有选择任何特定的TimeZone进行转换,任何文化格式都在使用转换DateTime值。

There is not any specific TimeZone selected for converting, any culture format was using converting DateTime value.

DateTimeFormatInfo ukDtfi = new CultureInfo(CultureInfo.CurrentCulture.ToString(), false).DateTimeFormat;
StartingDate = Convert.ToDateTime(System.Web.HttpContext.Current.Session["StartDate"].ToString(), ukDtfi);

我正在使用上述代码,但无法正常工作。
当前,我在系统中设置了 ar-SA 文化。

I am using above code but its not working properly. Currently I set ar-SA culture in my system.

推荐答案

让我先清除一些主题。

一个 DateTime 实例没有 any 时区信息和区域性设置。它 just 具有日期和时间值。文化设置概念仅在获得文本(字符串)表示形式时适用。

A DateTime instance does not have any timezone information and culture settings. It just have date and time values. Culture settings concept only applies when you get it's textual (string) representatiton.

由于使用了 ar-SA 文化,您的字符串格式不是那个文化的标准日期和时间格式。

Since you use ar-SA culture, your string format is not a standard date and time format for that culture.

var dt = DateTime.Parse("31/1/2016 12:00 AM", CultureInfo.GetCultureInfo("ar-SA"));
// Throws FormatException

无法解析具有 ar-SA 文化的字符串,因为此文化使用ص作为 AMDesignator ,因为它使用了 UmAlQuraCalendar 而不是 GregorianCalendar

And you can't parse this string with ar-SA culture because this culture uses ص as a AMDesignator since it uses UmAlQuraCalendar rather than a GregorianCalendar.

您可以使用 InvariantCulture (将 AM 用作 AMDesignator 并使用 GregorianCalendar )代替 DateTime.ParseExact 方法,并确切指定其格式。

You can use InvariantCulture (which uses AM as a AMDesignator and uses GregorianCalendar) instead with DateTime.ParseExact method with specify it's format exactly.

string s = "31/1/2016 12:00 AM";
DateTime dt = DateTime.ParseExact(s, "dd/M/yyyy hh:mm tt", 
                                  CultureInfo.InvariantCulture);

在您的情况下;

StartingDate = DateTime.ParseExact(System.Web.HttpContext.Current.Session["StartDate"].ToString(), 
                                   "dd/M/yyyy hh:mm tt", 
                                   CultureInfo.InvariantCulture);

这篇关于如何在不同的系统文化中转换DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆