简体   繁体   English

C#中的日期和时间格式

[英]Date and Time Formatting in c#

          int MM;
          int DD;
          int YYYY;
          switch(MM)
          {
                case 1:
                   DD = 31;
                   break;
                case 2:
                   DD = 28;
                   LDD = 29;
                   break;
                case 3:
                   DD = 31;
                   break;
                case 4:
                   DD = 30;
                   break;
                case 5:
                   DD = 31;
                   break;
                case 6:
                   DD = 30;
                   break;
                case 7:
                   DD = 31;
                   break;
                case 8:
                   DD = 31;
                   break;
                case 9:
                   DD = 30;
                   break;
                case 10:
                   DD = 31;
                   break;
                case 11:
                   days = 30;
                   break;
                case 12:
                   DD = 31;
                   break;
                default:
                   {
                            Console.WriteLine("Invalid option");
                   }
        }
        if(Date == MM/DD/YYYY)
        string Date = Console.ReadLine();

I am trying to write a code that would accept the date as string and only in this format mm/dd/yyyy and the time has to accepted only in this format 10:00AM By using DateTime i am getting the time in this format 10:00:00, the hour,minute,second format which i don't want. 我正在尝试编写一个将日期作为字符串并且仅以mm / dd / yyyy这样的格式来接受代码,并且仅以这种格式接受时间的代码。10:00 AM通过使用DateTime,我以这种格式获取时间10: 00:00,我不需要小时,分钟,秒格式。

I dont want to use try catch, exception. 我不想使用try catch,例外。

Use DateTime.ParseExact and write your format string following these guidlines: 使用DateTime.ParseExact并遵循以下准则编写格式字符串:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

您可以使用DateTime.ParseExact方法,并在其第二个参数中写入格式定义。

我建议使用DateTime.TryParseExact ,它将检查字符串是否符合您想要的格式,如果不是,则返回false,如果是,则返回true并填充您的日期。

You should go with DateTime.TryParseExact , as this method doesn't throws an exception for invalid dates: 您应该使用DateTime.TryParseExact ,因为此方法不会为无效日期引发异常:

DateTime parsed;
var input = "08/03/2013 08:30AM";
if (DateTime.TryParseExact(input, "MM/dd/yyyy hh:mmtt", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))
    Console.WriteLine("ok");
else
    Console.WriteLine("not ok");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM