在Windows应用程序中接受所有类型的日期时间

时间:2014-07-26 06:42:42

标签: c#-3.0

我在Windows应用程序中工作。我正在使用日期时间概念开发基于c#.net的简单通知系统。这个项目在我的系统中工作。我需要将datetime验证为dd / MM / yyyy,而在客户端系统错误中验证时,字符串不会被识别为有效的日期时间。因为客户端系统的格式为系统:dd MMMM yyyy

让我知道如何在我的项目中接受所有类型的日期时间格式..

二手代码:

public bool DateValidation(string stringDateValue)
{
    bool A = false;
    try
    {
         CultureInfo CultureInfoDateCulture = new CultureInfo("fr-FR");
         DateTime d = DateTime.ParseExact(stringDateValue, "dd/MM/yyyy", CultureInfoDateCulture);
         A = true;
    }
    catch
    {                   
         A = false;
    }
    return A;
}

1 个答案:

答案 0 :(得分:0)

如果这是在Windows客户端上,则不需要使用特定的文化。当应用程序启动时,Thread.CurrentThread.CurrentCulture会被设置为与客户区域设置匹配的文化。 DateTime.TryParse解析一个字符串并返回一个布尔值来表示成功或失败,同时还根据字符串创建一个DateTime结构。而不是保持stringDateValue(具有未确定的文化),您可以更好地调整您的代码,以便您可以使用该DateTime类型。

public bool DateValidation(string stringDateValue)
{   
   DateTime dtm; 
   bool success = DateTime.TryParse(stringDateValue, out dtm);
   // you might want to keep the `dtm` value, 
   // either by returning it instead of the bool,
   // our make it an out parameter on your method.
   return success;
}

如果您确实需要确保客户端应用程序中的所有日期都使用相同的日期时间格式,您可以通过在应用程序的开头设置CurrentCulture来强制应用程序使用特定的文化:

Thread.CurrentThread.CurrentCulture = new new CultureInfo("fr-FR");

并指示您的用户使用该文化中规定的日期格式(对于Shortdate pettern为dd/MM/yyyy的法语,对于长日期pettern为dddd d MMMM yyyy