Solved

VB.net loop through dates

Posted on 2014-11-23
4
1,444 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 32

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

746 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now