简体   繁体   中英

Converting from string to DateTime, and then storing in list C#

Been stuck on this task for a while now any help would be greatly appreciated.

So I have user input of Patient ID, Staff ID, visitType and DateTime from the Presentation Layer which I want to add to a list through the Business Layer.

The dateTime is inputted as a string and I can store It as a string fine but what I am trying to do is convert it into DateTime and then be able to store it in a list. this is where I encounter errors.

here is my code in presentation layer(MainWindow.cs), where I am pulling the information to be stored;

        private void BtnAddVisit_Click(object sender, RoutedEventArgs e)
        {
            txtOutput.Text = "";
            try
            {
                if (healthSystem.addVisit(new int[2] { 1, 3 }, 1, visitTypes.assessment, "01/01/2020 09:00")) //Should be OK
                    txtOutput.Text += "Visit 1 added.\n";
            }
            catch (Exception ex)
            {
                txtOutput.Text += ex.Message;
            }

            txtOutput.Text += healthSystem.getVisitList();
}

and here is my code in the business layer(HealthFacade);

public Boolean addVisit(int[] staff, int patient, int type, string dateTime)
        {
            //if the number of objects in the visit list is equal to 6, clear the list to avoid repeated output in textbox
            if (visit.Count == 6)
            {
                visit.Clear();
            }


            //converting from string to dateTime 
            for (int i = 0; i < visit.Count; i++)
            {
                //the original task was to store 6 instances so thats why is says < 7
                if (visit.Count < 7)
                {
                    DateTime oDate = Convert.ToDateTime(dateTime);

                }
            }

          
            //adding all the visits, regardless of if the data is valid or not
            Visit v = new Visit();
                v.Staff = staff;
                v.Patient = patient;
                v.Type = type;
                v.DateTime = oDate;  

                //adds instance of visit to the visit list
                visit.Add(v);


                return true;

My understanding would be that I would then write v.DateTime = oDate; but it tells me 'oDate' does not exist in the current context.

the code for my Visit class is here;

using System;
using System.Collections.Generic;
using System.Text;

namespace BusinessLayer
{
    class Visit
    {

        int[] staff;
        int patient, type;
        string dateTime;

        public Visit()
        {

        }


        // Constructor for Staff, using example from week 5 practical
        public Visit(int [] aStaff, int aPatient, int aType, string aDateTime)
        {
            staff = aStaff;
            patient = aPatient;
            type = aType;
            dateTime = aDateTime;

        }

        public int[] Staff
        {
            set { staff = value; }
            get { return staff; }
        }
        public int Patient
        {
            set { patient = value; }
            get { return patient; }
        }

        public int Type
        {
            set { type = value; }
            get { return type; }
        }

        public string DateTime
        {

            set { dateTime = value; }
            get { return dateTime; }
        }
    }
}

The reason I am trying to do this is so that I can set up a doctors appointments system and make sure that no 2 appointments are at the same time and therefore clash.

Thanks in advance for any help you can give!

The problem here is that the variable oDate only exists in the scope where you declared it. In your case it's only usable inside your if statement.

Your function should look like this for you to access the variable when needed:

public Boolean addVisit(int[] staff, int patient, int type, string dateTime)
    {
        //if the number of objects in the visit list is equal to 6, clear the list to avoid repeated output in textbox
        if (visit.Count == 6)
        {
            visit.Clear();
        }

        DateTime oDate = Convert.ToDateTime(dateTime);;
        //converting from string to dateTime 
        for (int i = 0; i < visit.Count; i++)
        {
            //the original task was to store 6 instances so thats why is says < 7
            if (visit.Count < 7)
            {
                //DateTime oDate = Convert.ToDateTime(dateTime);
                // Because you definded oDate inside your if clause it is only accessible inside the clause
            }
        }

      
        //adding all the visits, regardless of if the data is valid or not
        Visit v = new Visit();
            v.Staff = staff;
            v.Patient = patient;
            v.Type = type;
            v.DateTime = oDate;  

            //adds instance of visit to the visit list
            visit.Add(v);


            return true;

Convert.ToDateTime may not work with different local settings. Because a DateTime is not allways dd/MM/yyyy HH:mm.

You can try like this if you are sure that your datetime string is allways formatted like this "01/01/2020 09:00".

        var dateTime = "01/01/2020 09:00";//Assume your date is that.

        DateTime dtInvariant = DateTime.ParseExact(dateTime, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);

        //If you want to work with strings, 
        var datePart = dateTime.Split(' ')[0];
        var timePart = dateTime.Split(' ')[1];
        var day = int.Parse(datePart.Split('/')[0]);
        var month = int.Parse(datePart.Split('/')[1]);
        var year = int.Parse(datePart.Split('/')[2]);

        var hour = int.Parse(timePart.Split(':')[0]);
        var minute = int.Parse(timePart.Split(':')[1]);
        var myDate = new DateTime(year, month, day, hour,minute, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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