Solved

VB.net loop through dates

Posted on 2014-11-23
4
1,671 Views
Last Modified: 2016-02-18
Hi

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

Thanks
0
Comment
Question by:murbro
4 Comments
 
LVL 15

Expert Comment

by:ChloesDad
ID: 40460495
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
 
LVL 33

Expert Comment

by:it_saige
ID: 40460632
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
 
LVL 40

Accepted Solution

by:
Jacques Bourgeois (James Burger) earned 500 total points
ID: 40460799
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
 

Author Closing Comment

by:murbro
ID: 40461494
Thanks very much
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question