简体   繁体   English

C#Prinitng在控制台中修改了日期范围

[英]C# Prinitng modified date range in console

I need to accept input paramteters and print date range in console like in the example: 我需要在控制台中接受输入参数和打印日期范围,如示例所示:

input: "01.01.2017 05.01.2017" 输入:“ 01.01.2017 05.01.2017”

output: "01 - 05.01.2017" 输出:“ 01-05.01.2017”

So as you see dates must be separated with dots and printed with dash between them. 因此,如您所见,日期必须用点分隔,并在其之间打印破折号。 What is more, if start and end date both has the same month and year, these are printed only once. 此外,如果开始日期和结束日期都具有相同的月份和年份,则仅打印一次。

Does anyone can suggest good way to achieve this? 有谁能建议实现此目标的好方法?

Just format date as you need and add aditional check for cases. 只需根据需要设置日期格式,然后添加个案检查。

        DateTime date1 = new DateTime();
        DateTime date2 = new DateTime();

//while not valid input dates format...
        bool valid = false;
        while (!valid)
        {
            Console.WriteLine("Enter start date:");
            string dateEntered1 = Console.ReadLine();
            Console.WriteLine("Enter end date:");
            string dateEntered2 = Console.ReadLine();

             bool isvalidDate1 = DateTime.TryParse(dateEntered1,out date1);
            bool isvalidDate2 = DateTime.TryParse(dateEntered2,out date2);
//check if date parsing was sucess
            if(isvalidDate1 && isvalidDate2)
            {
                valid = true;
            }
            else
            {
                Console.WriteLine("Dates entered is in incorrect format!");

            }
        }
        string period = "";
        if (date1.Month == date2.Month && date1.Year == date2.Year)
        {
            period = string.Format("{0} - {1}", date1.ToString("dd."), date2.ToString("dd.MM.yyyy"));
        }
        else
        {
            period = string.Format("{0} - {1}", date1.ToString("dd.MM.yyyy"), date2.ToString("dd.MM.yyyy"));
        }
        Console.Write(period);
        Console.Read();

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

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