【问题标题】:TryParse returning true or false depending on computerTryParse 根据计算机返回真或假
【发布时间】:2014-08-29 19:13:02
【问题描述】:

我有一种验证日期时间的方法,它使用 tryParse 来执行此操作,问题是在我的计算机中,当验证格式为 dd/mm/yyyy 的日期和在另一台计算机中的格式为 mm/dd/yyyy 时返回 true它返回 false。

我该如何管理?

verifiyDate(String date)
   {
       DateTime temp;
       if (DateTime.TryParse(date.Trim(), out temp))
       {
           return true;
       }
       return false;
   }

【问题讨论】:

  • 问题是在另一台计算机上我无法更改格式,因为它是我不拥有更改格式权利的服务器。
  • 嗯,我不认为是电脑。您使用的是不同的格式。
  • 使用相同格式生成并验证日期。不管是哪一个。它必须是相同的。你的情况有可能吗?
  • 你试过 DateTime.TryParseExact 方法吗:msdn.microsoft.com/en-us/library/…

标签: asp.net sql datetime


【解决方案1】:

你这样说:

public static DateTime? ConvertToDate( this string s )
{
  const string   requiredFormat = @"dd/MM/yyyy" ;
  DateTimeStyles style          = DateTimeStyles.AllowLeadingWhite
                                | DateTimeStyles.AllowTrailingWhite
                                ;
  DateTime       converted      ;
  bool           parsed         = DateTime.TryParseExact(
                                    s ,
                                    requiredFormat ,
                                    CultureInfo.InvariantCulture ,
                                    style ,
                                    out converted
                                    ) ;
  DateTime?      value          = parsed ? converted : (DateTime?)null ;

  return value ;
}

它应该给你一个 DateTime 保存转换后的值,或者如果值无法转换,则为 null

【讨论】:

  • @user3816931 - 这绝对是 C#,但风格相当非传统。它也不会编译,但看起来它可能是从内存中输入的,这可以解释这一点。
  • @ChaosPandion:为你修正了错别字。鉴于 SO 的页面宽度较窄,该布局是为人类理解和避免水平滚动而设计的。
猜你喜欢
  • 1970-01-01
  • 2012-02-11
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
相关资源
最近更新 更多