VB.net loop through dates

Hi

I have two dates in string format. How do I loop through all the days between these dates?

Thanks
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ChloesDadCommented:
You first convert the strings to a date format. I have assumed that the string is in the correct format for your locale, as if its not then you have to use TryParse instead and pass in the format. The  loop through from the start date to the end date using OADate to convert the date to a number. Then use date.FromOADate to convert the date number back to a date.

startdate = new date.parse(startdatestring)
Enddate = new date.parse(Enddatestring)

for Loop = startdate.ToOADate to endDate.TOOADate

  LoopDate = date.fromOADate(Loop)

Next Loop

Open in new window

0
it_saigeDeveloperCommented:
Another way to do it using a Linq statement.  This also illustrates creating an extension method:
Module Module1
	Sub Main()
		Console.WriteLine("Using a function...")
		For Each [date] As DateTime In GetDates(DateTime.Now(), DateTime.Now.AddDays(10))
			Console.WriteLine([date].ToShortDateString())
		Next

		Console.WriteLine()
		Console.WriteLine("Using an extension method...")
		For Each [date] As DateTime In DateTime.Now().GetDates(DateTime.Now.AddDays(10))
			Console.WriteLine([date].ToShortDateString())
		Next

		Console.ReadLine()
	End Sub

	Public Function GetDates(ByVal start As DateTime, ByVal [end] As DateTime) As IEnumerable(Of DateTime)
		Dim dates As New List(Of DateTime)
		For Each [date] As DateTime In (From d In Enumerable.Range(0, [end].Subtract(start).TotalDays) Let now As DateTime = start.AddDays(d) Select now)
			dates.Add([date])
		Next
		Return dates
	End Function
End Module

Module Extentions
	<System.Runtime.CompilerServices.Extension()> _
	Public Function GetDates(ByVal start As DateTime, ByVal [end] As DateTime) As IEnumerable(Of DateTime)
		Dim dates As New List(Of DateTime)
		For Each [date] As DateTime In (From d In Enumerable.Range(0, [end].Subtract(start).TotalDays) Let now As DateTime = start.AddDays(d) Select now)
			dates.Add([date])
		Next
		Return dates
	End Function
End Module

Open in new window


Produces the following output:Capture.JPG
Ofcourse you could also add overloaded methods so that you can use strings, i.e. -
Module Module1
	Sub Main()
		Console.WriteLine("Using a function...")
		For Each [date] As DateTime In GetDates(DateTime.Now(), DateTime.Now.AddDays(10))
			Console.WriteLine([date].ToShortDateString())
		Next

		Console.WriteLine()
		Console.WriteLine("Using an extension method...")
		For Each [date] As DateTime In DateTime.Now().GetDates(DateTime.Now.AddDays(10))
			Console.WriteLine([date].ToShortDateString())
		Next

		Console.WriteLine()
		Console.WriteLine("Using a valid string that can be parsed as a datetime value.")
		For Each [date] As DateTime In "11/23/2014".GetDates(DateTime.Now.AddDays(10))
			Console.WriteLine([date].ToShortDateString())
		Next

		Console.WriteLine()
		Console.WriteLine("Using an invalid string that cannot be parsed as a datetime value.")
		For Each [date] As DateTime In "The brown cow".GetDates(DateTime.Now.AddDays(10))
			Console.WriteLine([date].ToShortDateString())
		Next

		Console.ReadLine()
	End Sub

	Public Function GetDates(ByVal start As DateTime, ByVal [end] As DateTime) As IEnumerable(Of DateTime)
		Dim dates As New List(Of DateTime)
		For Each [date] As DateTime In (From d In Enumerable.Range(0, [end].Subtract(start).TotalDays) Let now As DateTime = start.AddDays(d) Select now)
			dates.Add([date])
		Next
		Return dates
	End Function
End Module

Module Extentions
	<System.Runtime.CompilerServices.Extension()> _
	Public Function GetDates(ByVal start As String, ByVal [end] As String) As IEnumerable(Of DateTime)
		Dim _start As DateTime
		Dim _end As DateTime
		If Not DateTime.TryParse(start, _start) Then
			Console.WriteLine("Invalid start date; cannot parse string into a DateTime value.")
			Return New List(Of DateTime)
		End If

		If Not DateTime.TryParse([end], _end) Then
			Console.WriteLine("Invalid end date; cannot parse string into a DateTime value.")
			Return New List(Of DateTime)
		End If
		Return _start.GetDates(_end)
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function GetDates(ByVal start As String, ByVal [end] As DateTime) As IEnumerable(Of DateTime)
		Dim _start As DateTime
		If Not DateTime.TryParse(start, _start) Then
			Console.WriteLine("Invalid start date; cannot parse string into a DateTime value.")
			Return New List(Of DateTime)
		End If

		Return _start.GetDates([end])
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function GetDates(ByVal start As DateTime, ByVal [end] As String) As IEnumerable(Of DateTime)
		Dim _end As DateTime

		If Not DateTime.TryParse([end], _end) Then
			Console.WriteLine("Invalid end date; cannot parse string into a DateTime value.")
			Return New List(Of DateTime)
		End If
		Return start.GetDates(_end)
	End Function

	<System.Runtime.CompilerServices.Extension()> _
	Public Function GetDates(ByVal start As DateTime, ByVal [end] As DateTime) As IEnumerable(Of DateTime)
		Dim dates As New List(Of DateTime)
		For Each [date] As DateTime In (From d In Enumerable.Range(0, [end].Subtract(start).TotalDays) Let now As DateTime = start.AddDays(d) Select now)
			dates.Add([date])
		Next
		Return dates
	End Function
End Module

Open in new window


Will still produce the same results as above.  But in the case of an invalid string that cannot be parsed as a DateTime it will return an Empty List -Capture.JPG
-saige-
0
Jacques Bourgeois (James Burger)PresidentCommented:
ChloesDad code works, but is not optimal for performance. It shows his experience in VB classic (VB6) but is not optimal in .NET. It uses conversions from OA dates (Ole Automation), to enable a trick that programmers used in VB6, where the dates were recorded internally as a number of days from a reference date, which is not the case in .NET. FormOADate and ToOADate are meant to read and write binary files between old applications and .NET application, not to manipulate dates in .NET code.

It also goes through a Date object (New Date()) to call a static method (Parse) that are meant to be called directly on the type, preventing the need to create an object only to retrieve a value. Using Date.Parse instead of New Date.Parse requires les ressources and is also better performance wise.

You can do without having to convert to and from the old date format with the following code in .NET. Yes, it takes more code, but this is the way to work optimally with dates in .NET:
		Dim startDate As Date = Date.Parse(startDateString)
		Dim endDate As Date = Date.Parse(endDateString)
		Dim loopDate As Date = startDate

		While loopDate <= endDate
			'Do something with your loopDate, such as
			Debug.WriteLine(loopDate)
			loopDate = loopDate.AddDays(1)
		End While

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
Thanks very much
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.