Create a datatable with rows

RIAS
RIAS used Ask the Experts™
on
How to create a datatable with the time format string incremeted with nearest 15 minutes.
I am using vb.net

example:

Dim dt as new datatable

If the string value is 2:32 then the datatable should have rows in time incrementing by around 15 minutes :

Having rows like :

2:45
3:00
3:15

example2:
String value is 4:34 then the datatable should have rows in time incrementing by around 15 minutes :

Having rows like :

4:45
5:00
5:15

Please let me know if you have any further queries.

Regards
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Is the "2:32" string part of some larger object? Or are you creating a new data table from one, standalone string value?

Also you said the "nearest 15 minutes" but for 2:32, the nearest 15 minute interval is 2:30. So are you wanting the next highest 15 minute interval?

Author

Commented:
Is the "2:32" string part of some larger object? Or are you creating a new data table from one, standalone string value?

Yes,I am creating  a new data table from one, standalone string value?

Also you said the "nearest 15 minutes" but for 2:32, the nearest 15 minute interval is 2:30. So are you wanting the next highest 15 minute interval?
 So are you wanting the next highest 15 minute interval? Yes absolutely .


Thanks a lot for getting back

Author

Commented:
Also gr8gonzo,

The incrementing should stop at 3:00 of next day.

example:

String value is 9:02 on Saturday  then the rows in the datatable should be

09:15
09:30
09:45
'
'
03:00  Sunday

Thanks
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

Author

Commented:
Really appreciate your help .

Commented:
Okay. I'm not in front of my workstation at the moment but I can explain how you would do this.

First you would split your string on the colon:
Dim parts As String() = yourtimestring.Split(New Char() {":"c})

Then you would access the second part to get the minutes:
Dim strMinutes as String = parts(1)

Then you would convert the string "32" to the number 32:
Dim intMinutes As Integer = Integer.Parse(strMinutes)

From there you would divide that value by 15 to see how many "full" 15 minute blocks have elapsed. So in the example of "2:32", 32 minutes has two full 15 minute blocks that have elapsed, so our starting minute block is "30":

Dim intBlocks = intMinutes / 15;
Dim intStartingMinuteBlock = intBlocks * 15

Then we can reconstruct the time "2:30":
Dim strStartingTime = parts(0) + ":" + intStartingMinuteBlock.ToString("00")

And convert "2:30" it to a DateTime:
Dim dtStart = DateTime.Parse(strStartingTime)

Then if our original minutes (32) is greater than our starting block (30) then we can increment the DateTime to the next 15 minute block:
if(intMinutes > intStartingMinuteBlock)
{
  dtStart.AddMinutes(15)
}

From here you can use a basic For loop to just increment dtStart by 15 minutes and use dtStart.ToString("desired format here") to create the list of strings like "2:45”, "3:00", "3:15" etc...

And once you have the list, you can loop through it to create the datarows based on that string.

Again, I'm not in front of my PC so the above code might need some tweaking but it should be pretty close.

Author

Commented:
Yes definitely, will give a try and really appreciate your help!

Commented:
Using Gonzo's proposal and adding in a DataTable extension method; this code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;

namespace EE_Q29156752
{
    class Program
    {
        static void Main(string[] args)
        {
            var start = "2:32";
            var times = (from interval in Enumerable.Range(1, 48 * 60 / 15)
                         let origin = DateTime.Parse($"{DateTime.Parse(start).Hour}:{DateTime.Parse(start).Minute / 15 * 15}")
                         let endTime = new DateTime(origin.AddDays(1).Year, origin.AddDays(1).Month, origin.AddDays(1).Day, 15, 0, 0)
                         let startTime = DateTime.Parse($"{origin.Hour}:{origin.Minute / 15 * 15}").AddMinutes(interval * 15)
                         where startTime <= endTime
                         select new { StartTime = startTime }).ConvertToDataTable();

            foreach (DataRow time in times.Rows)
            {
                Console.WriteLine(Convert.ToDateTime(time["StartTime"]).ToString("hh:mm:ss"));
            }
            Console.ReadLine();
        }
    }

    static class Extensions
    {
        public static DataTable ConvertToDataTable<T>(this IEnumerable<T> source, string name = "")
        {
            DataTable table = new DataTable(name);
            var properties = TypeDescriptor.GetProperties(typeof(T));
            foreach (PropertyDescriptor property in properties)
            {
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    table.Columns.Add(property.Name, property.PropertyType.GetGenericArguments()[0]);
                }
                else
                {
                    table.Columns.Add(property.Name, property.PropertyType);
                }
            }

            object[] values = new object[properties.Count];
            foreach (var item in source)
            {
                for (int i = 0; i < properties.Count; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }
                table.Rows.Add(values);
            }
            return table;
        }
    }
}

Open in new window

Produces this output -Capture.PNGCapture.PNG-saige-

Author

Commented:
Sir,
Thanks a lot!!!
Will try and brb .

Commented:
Actually, no need to parse the DateTime a third time.  This would also suffice (change on line 17):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;

namespace EE_Q29156752
{
    class Program
    {
        static void Main(string[] args)
        {
            var start = "2:32";
            var times = (from interval in Enumerable.Range(1, 48 * 60 / 15)
                         let origin = DateTime.Parse($"{DateTime.Parse(start).Hour}:{DateTime.Parse(start).Minute / 15 * 15}")
                         let endTime = new DateTime(origin.AddDays(1).Year, origin.AddDays(1).Month, origin.AddDays(1).Day, 15, 0, 0)
                         let startTime = origin.AddMinutes(interval * 15) // No need to parse again here, just use origin
                         where startTime <= endTime
                         select new { StartTime = startTime }).ConvertToDataTable();

            foreach (DataRow time in times.Rows)
            {
                Console.WriteLine(Convert.ToDateTime(time["StartTime"]).ToString("hh:mm:ss"));
            }
            Console.ReadLine();
        }
    }

    static class Extensions
    {
        public static DataTable ConvertToDataTable<T>(this IEnumerable<T> source, string name = "")
        {
            DataTable table = new DataTable(name);
            var properties = TypeDescriptor.GetProperties(typeof(T));
            foreach (PropertyDescriptor property in properties)
            {
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    table.Columns.Add(property.Name, property.PropertyType.GetGenericArguments()[0]);
                }
                else
                {
                    table.Columns.Add(property.Name, property.PropertyType);
                }
            }

            object[] values = new object[properties.Count];
            foreach (var item in source)
            {
                for (int i = 0; i < properties.Count; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }
                table.Rows.Add(values);
            }
            return table;
        }
    }
}

Open in new window

-saige-

Author

Commented:
Thanks
     Private Function CreateDataTable(timeStart As String) As DataTable
        Dim ts As TimeSpan
        If Not TimeSpan.TryParseExact(timeStart, "h\:mm", Nothing, ts) Then Return Nothing
        Dim mins = ts.TotalMinutes
        mins = If(mins Mod 15 = 0, mins, (Math.Floor(ts.TotalMinutes / 15) + 1) * 15)
        Dim table = New DataTable()
        table.Columns.Add("Time", GetType(String))
        Do While ts.TotalHours < 27
            ts = TimeSpan.FromMinutes(mins)
            table.Rows.Add(ts.ToString("h\:mm"))
            mins += 15
        Loop
        Return table
    End Function

Open in new window

Using:
DataGridView1.DataSource = CreateDataTable("2:32")

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial