代码之家  ›  专栏  ›  技术社区  ›  Zo Has

将文本转换为日期时间?

  •  2
  • Zo Has  · 技术社区  · 14 年前

    myFtMaster.GENTRTYDATEFROM =Convert.ToDateTime(txtTreatyPeriodfrom.Text.ToString());
    

    我的业务对象“gentrtydatefrom”数据类型是DateTime。另外,在不使用Try-catch块的情况下避免此类错误的最佳方法是什么。

    3 回复  |  直到 14 年前
        1
  •  3
  •   Guffa    14 年前

    您可以指定使用该特定格式的区域性:

    myFtMaster.GENTRTYDATEFROM = Convert.ToDateTime(
      txtTreatyPeriodfrom.Text, CultureInfo.GetCulture("en-GB")
    );
    

    或者使用 ParseExact

    myFtMaster.GENTRTYDATEFROM = DateTime.ParseExact(
      txtTreatyPeriodfrom.Text, "dd/MM/yyyy", CultureInfo.Invariant
    );
    

    精确解析 Convert.ToDateTime 方法仍然允许对格式进行一些更改,并且还接受其他一些日期格式。

    要捕获非法输入,可以使用 TryParseExact

    DateTime d;
    if (DateTime.TryParseExact(txtTreatyPeriodfrom.Text, "dd/MM/yyyy", CultureInfo.Invariant, DateTimeStyles.None, out d)) {
      myFtMaster.GENTRTYDATEFROM = d;
    } else {
      // communcate the failure to the user
    }
    
        2
  •  3
  •   Joe Ratzer    14 年前

    请改用以下方法:

            DateTime date = DateTime.MinValue;
            DateTime.TryParse(txtTreatyPeriodfrom.Text, out date);
    

    锥虫类似于 DateTime.Parse()

    如果要使用en-CA特定区域性,请使用以下内容:

    DateTime.TryParse(txtTreatyPeriodfrom.Text, new CultureInfo("en-CA"), 
                    DateTimeStyles.AllowWhiteSpaces, out date); 
    

    然后很明显要处理那些无法解析的日期。

        3
  •  2
  •   cjk    14 年前

    看一看

    DateTime.TryParse(String value, out DateTime, [culture settings])