【问题标题】:Format dateTimePicker like yyyy-yyyy (2020/2021) c#格式 dateTimePicker 像 yyyy-yyyy (2020/2021) c#
【发布时间】:2021-06-14 06:01:27
【问题描述】:

我正在为大学做一个项目,它是年鉴项目。我需要以精确的格式 yyyy/yyyy(例如 2020/2021)输入年份,谁能帮我解析并进行验证?

【问题讨论】:

  • 什么意思?你能分享你的代码吗?
  • 你为什么要首先在DateTimePicker 中这样做?只是有一个包含年份列表的下拉列表?
  • @DavidG 感谢这个想法

标签: c# asp.net visual-studio


【解决方案1】:

您可以使用正则表达式进行验证:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] values= { "2020/2021", "2019-2020", 
                              "199e-2000" };
      Regex rgx = new Regex(@"^\d{4}(/\d{4})"); // 4 digits, forward slash, 4 digits
      foreach (string value in values)
         Console.WriteLine("{0} {1} a valid entry.", 
                           value, 
                           rgx.IsMatch(value) ? "is" : "is not");
   }
}
// The example displays the following output:
//      2020/2021 is a valid entry.
//      2019-2020 is not a valid entry.
//      199e-2000 is not a valid entry.

【讨论】:

    【解决方案2】:
            bool CheckDateYear(string s)
            {
                string s1 = s.Split('/')[0];//s.Split('-')[0]
                string s2 = s.Split('/')[1];
                if (DateTime.Now.Year.ToString() != s2 || (DateTime.Now.Year - 1).ToString() != s1)
                    return false;
                else
                    return true;
            }
    
    ...
    
           if(CheckDateYear("2020/2021")
           {
              ...
           }
    

    【讨论】:

      猜你喜欢
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      相关资源
      最近更新 更多