Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

VB.net loop through dates

Posted on 2014-11-23
4
Medium Priority
?
2,099 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:Murray Brown
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 35

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 2000 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:Murray Brown
ID: 40461494
Thanks very much
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

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

Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

972 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