Minal Modi
Minal Modi

Reputation: 25

How to parse by one line?

I am looking for a solution about how to get all of my int Parses within one line. At the moment when I start my program I have to enter day, month and year. It is all done line by line. I want a solution or method where this does all of my parsing within one line and within a format of "dd/MM/yyyy".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace date
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("please enter date as dd/MM/yyyy");

            int day;
            int month;
            int year;


            day = int.Parse(Console.ReadLine());
            month = int.Parse(Console.ReadLine());
            year = int.Parse(Console.ReadLine());
            Date i = new Date(day, month, year);



            Console.WriteLine("{0}/{1}/{2}", i.day, i.month, i.year);
            Console.ReadLine();
        }

        class Date
        {
            public int month; // 1-12
            public int day; // 1-31 depending on month
            int value = 1;

            public int year
            {
                get;
                private set;
            }


            public Date(int day, int month, int year)
            {
                this.day = day;
                this.month = month;
                this.year = year;
            }

            public int GetYear()
            {
                return year;
            }

            public void SetYear()
            {
                if (value > 1900 && value <= 2020)
                    year = value;
                else
                    throw new ArgumentOutOfRangeException("year", value, "out of bounds");
            }

            private int Month
            {
                get { return month; }
                set
                {
                    if (value > 0 && value <= 12)
                        month = value;
                    else
                        throw new ArgumentOutOfRangeException("Month", value, "Month must be 1-12");
                }
            }

            public int GetDay()
            {
                return day;
            }

            public void SetDay()
            {
                int[] days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

                if (value > 0 && value <= days[month])
                    day = value;

                else if (month == 2 && value == 29 &&
                    year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
                    day = value;
                else
                    throw new ArgumentOutOfRangeException("days", value, "day is out of range");
            }

        }

    }

}

Upvotes: 0

Views: 558

Answers (3)

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

You can't parse dd/MM/yyyy formatted string to int because it is not a valid string.

You need to parse it to DateTime first and you can use it's properties to get it's day, month and year as a numbers.

For example;

Console.WriteLine("please enter date as dd/MM/yyyy");
DateTime dt = DateTime.ParseExact(Console.ReadLine(), "dd/MM/yyyy",
                                  CultureInfo.InvariantCulture);

int day = dt.Day;
int month = dt.Month;
int year = dt.Year;

Or you can use TryParseExact if you don't wanna throw exception if input is not dd/MM/yyyy format.

I am not wanting to use the preset DateTime class but I am using my own "Date" class

If so, after you parse it, you can create your Date class instance with Date(int day, int month, int year) constructor based on this dt value as;

Date myDt = new Date(dt.Day, dt.Month, dt.Year);

Upvotes: 0

Slyvain
Slyvain

Reputation: 1732

If you do NOT want to use DateTime.(Try)Parse, you can add a parse method with a Regex in your Date class:

public static Date ParseFromString(string s)
  {
     //string s = "24/12/2015";
     Regex r = new Regex(@"(\d+)[\/](\d+)[\/](\d+)");
     Match m = r.Match(s);
     if (m.Success)
     {
        return new Date(m.Groups[1], m.Groups[2], m.Groups[3]);
     }
     else
     {
         // throw exception
     }
  }

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use DateTime.Parse/TryParse or DateTime.ParseExact/TryParseExact:

string line = Console.ReadLine();
DateTime dt;
bool validDate = DateTime.TryParseExact(line,"dd/MM/yyyy", DateTimeFormatInfo.InvariantInfo,DateTimeStyles.None, out dt);
if(validDate)
    Console.WriteLine(dt.ToLongDateString()); // now correctly initialized 

With this format also DateTime.Parse/DateTime.TryParse works:

validDate = DateTime.TryParse(line, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt);

I use DateTimeFormatInfo.InvariantInfo to prevent that your local date separator is used instead of /(in case it's different).

Once it is parsed to DateTime it's trivial to create your Date instance:

Date d = new Date(dt.Day, dt.Month, dt.Year);

Upvotes: 1

Related Questions