Solved

VB.net loop through dates

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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Suggested Solutions

I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

813 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

16 Experts available now in Live!

Get 1:1 Help Now