[英]DateTime - How can i account for different delimiter characters
My application is taking the time now, formatting it into a string, and parsing it back to a valid DateTime value using ParseExact. 我的应用程序现在花时间,将其格式化为字符串,然后使用ParseExact将其解析回有效的DateTime值。 See below for more details: 请参阅下面的更多细节:
DateTime dt = DateTime.Now;
DateTime timeNow = DateTime.Now;
string timeStamp = dt.ToString("MM/dd/yyyy HH:mm:ss");
// To match different countries
if (timeStamp.IndexOf("/") > -1)
{
timeNow = DateTime.ParseExact(timeStamp, "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
}
else if (timeStamp.IndexOf(".") > -1)
{
timeNow = DateTime.ParseExact(timeStamp, "MM.dd.yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
}
Different countries use different date formats. 不同的国家使用不同的日期格式。 Is there a way to make my application automatically take into account the different formats, rather than having to make a condition for each one that appears? 有没有一种方法可以使我的应用程序自动考虑不同的格式,而不必为出现的每种格式都设置一个条件?
Thanks for any help, 谢谢你的帮助,
Evan 埃文
If your application is using a string representation for dates internally, I would suggest using the Sortable format specifier when outputting it. 如果您的应用程序内部使用日期的字符串表示形式,则建议在输出时使用Sortable格式说明符 。 That way, you always know that you can read it back using ParseExact
and the "s"
format specifier. 这样,您始终知道可以使用ParseExact
和"s"
格式说明符将其读回。
The only time you should output dates in any other format is when you need to display them for the user, or when some other program requires them in a particular format. 您唯一应该以任何其他格式输出日期的时间是何时需要为用户显示日期,或者某些其他程序要求以特定格式显示日期。
As @Mike Christensen pointed out in his comment, different locales will interpret dates differently. 正如@Mike Christensen在其评论中指出的那样,不同的语言环境对日期的解释也不同。 The default output for many European countries is DD/MM/YYYY, whereas in the US it's usually MM/DD/YYYY. 许多欧洲国家/地区的默认输出为DD / MM / YYYY,而在美国,通常为MM / DD / YYYY。 If you take the different locales into account, then there will be ambiguity. 如果考虑到不同的语言环境,则将存在歧义。
You can pass an array of format specifiers with as many formats as you want to support. 您可以传递格式说明符数组,其中包含要支持的格式。
string[] formats = new [] { "MM/dd/yyyy HH:mm:ss", "MM.dd.yyyy HH:mm:ss" };
DateTime d = DateTime.ParseExact
(
timestamp, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
However, since you say you are generating the strings yourself, why don't you just make sure you always format them using the InvariantCulture: 但是,由于您说自己在生成字符串,所以为什么不确保始终使用InvariantCulture格式化它们:
string timestamp = dt.ToString("MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.