In VB6, I am trying to add days to a date which is in the format 'YYYYMMDD'. I can add days like this:
Pull_Date = Need_Date + Val(txtLeadTime.Text)
which works, until the resulting days is greater than the number of days in the month. I tried using DateAdd, but it doesn't accept the YYYYMMDD format - neither does CDate.
You need to convert your date string to a date so you can use the DateAdd function:
Dim Need_Date As String
Dim Pull_Date As Date
Dim tmpDate As Date
Need_Date = "20141113"
tmpDate = CDate(Mid$(Need_Date, 5, 2) & "/" & Right$(Need_Date, 2) & "/" & Left$(Need_Date, 4))
Pull_Date = DateAdd("d", Val(txtLeadTime.Text), tmpDate)
MsgBox Format$(Pull_Date, "yyyymmdd") '// if LeadTime is 25 days, displays 20141208
Please note, parsing your Need_Date by character position can blow up if it's not formatted exactly as expected.
After digging deeper into this old code, I found that a conversion function was already created:
Public Function Date_Format_YYYYMMDD(ByVal sDate As String) As String
If IsDate(sDate) Then
sDate = Format(sDate, "YYYYMMDD")
End If
Date_Format_YYYYMMDD = sDate
End Function
With this function, it's really easy:
Pull_Date = Date_Format_YYYYMMDD(Need_Date) + Val(txtLeadTime.Text)
The only thing I don't understand is why
Pull_Date = Format(Need_Date, "YYYYMMDD") + Val(txtLeadTime.Text)
doesn't work. Seems like it's doing the same thing as the function.
Related
Trying another attempt at this question:
With the below code, I'm trying to articulate a date range; May 10 - June 8th. I'm outputting a unique thumbnail image per date in this range (coming together as a stylized calendar of sorts); I need to also detect, within this range, today's date. As a .today style class will be appending for today's date. I achieved this previously when the date range was just within one month, 1 - 31 (and that code is under the most recent attempt / which is original code) this same code could not work because now it's not as simple as 1 - 31 and declaring the month name statically, now it's two months and 10 - 31 and then 1 - 8. Also, not my most recent attempt fails so hard the page doesn't even compile and is just white.
<%
Dim d1 As New Date(2015, 5, 10)
Dim d2 As New Date(2015, 6, 8)
Dim DaysBetween As Long = DateDiff(DateInterval.Day, d1, d2)
Dim d3 As Date
For d As Long = 0 To DaysBetween
d3 = d1.AddDays(d)
If d3 < Today() Then
time = "past"
ElseIf d3 = Today Then
time = "today"
Else
time = "future"
End If
Dim suffix As String = Suffixer(d3.Day)
response.write("<section id='day_"& i &"' class='calSquare " & time &"'><article class='dateImage' style='background-image: url(images/Calendar_Thumbnails/Day_"&i&".jpg)'></article></article><article class='dateTitle'> "&i&suffix&"</article></section>")
Next
<!--response.write(products(0))-->
%>
Original functional code; articulating one month.
<%
For i = 1 to 31
dim time
If i < day_part Then
time = "past"
ElseIf i = day_part Then
time = "today"
Else
time = "future"
End If
suffix = Suffixer(i)
response.write("<section id='day_"& i &"' class='calSquare " & time &"'><article class='dateImage' style='background-image: url(images/Calendar_Thumbnails/Day_"&i&".jpg)'></article></article><article class='dateTitle'>May "&i&suffix&"</article></section>")
Next
<!--response.write(products(0))-->
%>
Your first code sample isn't valid VBScript. The language doesn't support constructs like Dim var As type = value, so that's probably why the page isn't displayed.
As for listing the dates within a range while highlighting the current date, you could do something like this:
today = Date
firstDay = DateValue("2015-05-10")
lastDay = DateValue("2015-06-08")
d = firstDay
While d <= lastDay
If d = today Then
response.write "today"
Else
response.write "other day in range"
End If
d = d + 1
Wend
I need help with a quick question I a string "07/10/2014" how can I get first the year "2014",second the month "10" ,third the day- "07" with out "/" only the values in VB.NET
Please show me the full way how to do it.
First declare it like this Dim x as Date = "07/10/2014". And to get the individual values use x.Day, x.Month and x.Year
Use the DateTime.Parse() method then use the return DateTime structure to extract the Month, Day, Year properties (similar to DJK's answer above).
If the thread's current culture is set to one that understands "mm/dd/yyyy" format, then the code can be as simple as:
Dim dt As DateTime = DateTime.Parse("07/15/2014")
MessageBox.Show(String.Format("Month: {0}; Day: {1}; Year: {2}", dt.Month, dt.Day, dt.Year))
Have a look at this.
Dim MyDate As Date
MyDate = "07/10/2014"
MsgBox(Format(MyDate, "dd")) ' dd gives you day number
MsgBox(Format(MyDate, "MM")) ' MM gives you month number
MsgBox(Format(MyDate, "YYYY")) ' YYYY gives you year number
The full list of date fomatting string could be found here (MSDN)
UPDATE
Use following example to assign to a string variable
Dim DayOfString As String DayOfString
DayOfString = Format(MyDate, "dd")
I need to create some sort of a calendar in VBA.
I need to create a column of hours. The time difference between 2 adjacent cells is determined by an integer read from a text file, which represents the time resolution in minutes.
For example - if Res = 60, the hour column should look like this:
12:00
13:00
14:00
...
if Res = 30, the hour column should look like this:
12:00
12:30
13:00
13:30
14:00
....
I've calculated the number of cells according to the given resultion (if Res = 60, nCells = 24, if Res = 30 nCells = 48 and so on). I just don't know how to create the hour column (in VBA code of course).
Thanks,
Li
You could use DateAdd to increment dates: http://www.techonthenet.com/excel/formulas/dateadd.php
Sub createTimeColumn()
intIncr = 60 'minutes to add each cell
intCellCnt = 1440 / intIncr '24h * 60m = 1440 minutes per day
datDate = CDate("01/11/2013 06:00:00") 'start date+time for first cell
For i = 1 To intCellCnt 'loop through n cells
Cells(i, 1) = Format(datDate, "hh:mm") 'write and format result
datDate = DateAdd("n", intIncr, datDate) 'add increment value
Next i
End Sub
Result will look like
You need a simple loop to which you pass the start range, begin & end time and increment. I recommend to strictly work with dates/times; the output range should be formatted as time
Sub CallTest()
FillIt [A1], #12:00:00 PM#, #1:00:00 PM#, #12:10:00 AM#
End Sub
Sub FillIt(RStart As Range, TStart As Date, TEnd As Date, Inc As Date)
Dim Idx As Integer, TLoop
Idx = 1
TLoop = TStart
Do
RStart(Idx, 1) = TLoop
TLoop = TLoop + Inc
Idx = Idx + 1
Loop Until TLoop > TEnd + #12:00:01 AM# ' need to add 1 second to really
' break the loop where we want
End Sub
Don't worry about the somewhat strange looking Inc parameter .... in VBA editor just enter #0:10:0# ... it will automatically expand to a full 24 hrs AM/PM notation.
The 1 second in the Loop Until is added because I found that the loop is left 1 pass too early (it seems that within the loop #16:0:0# < #16:0:0# resolves to True)
Public Sub MakeTime(RangeA As Range, iRes As Long)
Dim dDate As Date
Dim rCell As Range
Dim X As Variant
Set rCell = RangeA
dDate = CDate(RangeA.Value)
Do
dDate = DateAdd("n", iRes, dDate)
Set rCell = rCell.Offset(1, 0)
rCell.Value = dDate
Loop Until DateDiff("h", CDate(RangeA.Value), dDate) >= 24
End Sub
Sub test()
Call MakeTime(Sheet1.Range("A1"), 45)
End Sub
They beat me to it... But since I've already written a routine... Might as well post it :)
Try this in a new workbook
Sub Main()
' ask for column input
Dim myColumn As String
myColumn = InputBox("Please enter the column letter where the hours will be stored")
' Clear the column
Columns(myColumn & ":" & myColumn).ClearContents
' initial hour
Dim firstHour As String
firstHour = InputBox("Please enter the start time in the hh:mm format i.e. 12:00")
' interval
Dim interval As Long
interval = CLng(InputBox("Please enter the interval in minutes"))
' duration
Dim duration As Long
duration = CLng(InputBox("Please enter the duration (hrs)"))
' apply formatting to column
Columns(myColumn & ":" & myColumn).NumberFormat = "hh:mm;#"
' enter the initial time into cell
Range(myColumn & 1) = CDate(firstHour)
' fill in remaining hours / interval
Dim i As Long
For i = 1 To (60 / interval) * duration
Range(myColumn & 1).Offset(i, 0) = DateAdd("n", interval, CDate(Range(myColumn & 1).Offset(i - 1, 0)))
Next i
End Sub
I have 2 columns, one for start-time and the other for the end-time. They both are of the type nvarchar so that i can compare them.
I have a text box that will receive time from the user and will post-back automatically to check if the the time is valid or not.
Dim compared_time_1 As DateTime
Dim compared_time_2 As DateTime
Dim select_time As SqlCommand
select_time = New SqlCommand("select Start_Time , End_Time from Clinic_Schedule where Schedule_no = #sch_no", appt_DB_1)
select_time.Parameters.AddWithValue("#sch_no", Sch_no)
Dim time_rdr As SqlDataReader
time_rdr = select_time.ExecuteReader()
While time_rdr.Read
compared_time_1 = DateTime.Parse(start_time_1)
compared_time_2 = DateTime.Parse(end_time_1)
start_time_1 = time_rdr(0).ToString
end_time_1 = time_rdr(1).ToString
If appt_time_txt0.Text >= start_time_1 And appt_time_txt0.Text <= end_time_1 Then
date_valid_lbl0.Visible = True
date_valid_lbl0.Text = "*Valid Time"
Else
time_valid_lbl0.Visible = True
time_valid_lbl0.Text = "*Not Valid Time"
End If
End While
time_rdr.Close()
I don't know if i have a problem with my logic XD.
the data filled in thoses columns are in this format : 00:00AM or 00:00PM.
I will appreciate your help .. thanks
Seems like you are comparing a string against a date datatype.
Ensure that you are converting both into date datatype as follows.
Note the space between the seconds and 'AM'.
time1=CDate("3:19:40 AM")
time2=CDate("3:10:40 AM")
Then perform comparisms as follows:
if time1>time2 then
'logic
end if
It looks like you're doing the parse before loading the data from your reader.
compared_time_1 = DateTime.Parse(start_time_1)
compared_time_2 = DateTime.Parse(end_time_1)
start_time_1 = time_rdr(0).ToString
end_time_1 = time_rdr(1).ToString
should be
start_time_1 = time_rdr(0).ToString
end_time_1 = time_rdr(1).ToString
compared_time_1 = DateTime.Parse(start_time_1)
compared_time_2 = DateTime.Parse(end_time_1)
But I would even do it differently than that. If you're trying to tell if the times are valid, you can use the datetime TryParse method. Perhaps a bit of refactoring might also help you. Finally, just be aware that comparing times might be problematic if there is ever a chance that schedule item might begin before midnight and end after midnight the next day.
Sub ReadingData()
'initializing reader stuff here...
Dim dtStart As DateTime, dtEnd As DateTime
If DateTime.TryParse(time_rdr(0).ToString, dtStart) = False Then
HandleInvalidTime()
End If
If DateTime.TryParse(time_rdr(1).ToString, dtEnd) = False Then
HandleInvalidTime()
End If
'Closing out reader stuff here...
HandleValidTime(dtStart, dtEnd)
End Sub
Sub HandleValidTime(TheStartTime As DateTime, TheEndTime As DateTime)
'Do Stuff
End Sub
Sub HandleInvalidTime()
'Do Stuff
End Sub
I'm trying to convert a string into a date format
My string looks like this
Dim MyString as String = "June 2011"
And I'm trying to convert it like this
Convert.ToDateTime(MyString).ToString("MM yyyy")
But it's giving me the error
Syntax error converting datetime from
character string.
The desired output would be either 06/2011 or 01/06/2011. The value of my string will only ever have the month and year in though.
Any ideas?
A datetime object in .NET represents one single point in time. To create one from a Gregorian calendar date, you need all three parts (day, month, year), otherwise it can't represent one single point in time.
Since your business requirement is to assume that the day number is 1 if not provided, just insert that number into the string before parsing.
Dim myDate As Date = Convert.ToDateTime("1 " & MyString)
EDIT:
Sorry, forgot to mention that string manipulations like that are of course culture-dependent. You don't mention what culture you are in. "June 2011" can imply either en-GB or en-US. Since inserting the day number at the start of the string is easier than trying to insert it between the month and year, I suggest you go for something like this.
Dim myDate1 As Date = Date.Parse("1 " & myString, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.AllowWhiteSpaces)
Convert.ToDateTime() only takes the full date so try prepending 01 as the day first i.e.
Convert.ToDateTime("01 " + MyString)
DateTime.Parse(MyString).ToString("MM yyyy")
This worked for me
Dim provider As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture
Dim MyString As String
Dim d As DateTime = DateTime.Now 'test start
'test all Month Year strings
For x As Integer = 1 To 12
MyString = d.ToString("MMMM yyyy") 'convert date to March 2011 then April 2011 then...
Dim dt As DateTime = DateTime.ParseExact(MyString, "MMMM yyyy", provider)
Debug.WriteLine(MyString & " " & dt.ToString)
d = d.AddMonths(1)
Next