Saturday 28 September 2013

Refine Hours and Min from user give value

Hi All,

Today I am going to give a method by the help of which you can get hours and mins as integer if user willl give in different formate like, (1 hr 10 min or 1hr or 1:10 hour...)



public void getEventHourAndMinuteValues(string eventDuration, out int hour, out int minutes)
        {
            hour = 0;
            minutes = 0;

            try
            {
                if (eventDuration != string.Empty)
                {
                label1:
                    string[] duration = eventDuration.Split(new char[] { ':','.' });
                    if (IsValidTime(eventDuration))
                    {
                        if (duration.Length > 1)
                        {
                            hour = Convert.ToInt32(duration[0]);
                            minutes = Convert.ToInt32(duration[1]);
                        }
                        else
                        {
                            hour = Convert.ToInt32(duration[0]);
                        }
                    }
                    else
                    {
                        string pattern = @"(hour|HRs|hr|hrs|hr's|HOUR|HR)";
                        string minPattern = @"(minutes|mins|min's|Minutes|MINUTES)";
                        if (duration.Length > 1)
                        {
                            duration[0] = Regex.Replace(duration[0], @"\s+", string.Empty); //removing whitespace
                            duration[1] = Regex.Replace(duration[1], @"\s+", string.Empty);
                            hour = Convert.ToInt32(Regex.Replace(duration[0], pattern, string.Empty));
                            minutes = Convert.ToInt32(Regex.Replace(duration[1], minPattern, string.Empty));
                        }
                        else
                        {
                            //duration[0] = Regex.Replace(duration[0], @"\s+", string.Empty); //removing whitespace
                            try
                            {
                                hour = Convert.ToInt32(Regex.Replace(duration[0], pattern, string.Empty));
                            }
                            catch
                            {
                                hour = 1;
                                //eventDuration = Regex.Replace(duration[0], pattern, ":");
                                //eventDuration = Regex.Replace(eventDuration, minPattern, string.Empty);
                                //eventDuration = Regex.Replace(eventDuration, @"\s+", string.Empty); //removing whitespace
                                ////goto label1;
                            }
                        }

                    }
                }
                else
                {
                    hour = 1;
                }

            }
            catch (Exception ex)
            {
                hour = 1;
            }

        } 

No comments:

Post a Comment