This question already has an answer here:
Format of a date used for initialisation
(1 answer)
Closed 3 years ago.
I'm passing my variables in the following order:
FileEndDate StartDateRange EndDateRange
FileEndDate = 10/11/2019
StartDateRange = 01/04/2019
EndDateRange = 30/04/2019
However, my code returns 'True', despite the fact that 10/11/2019 should not be in the date range of 01/04/2019 -> 30/04/2019.
If (WScript.Arguments.Item(0) >= WScript.Arguments.Item(1)) And (WScript.Arguments.Item(0) <= WScript.Arguments.Item(2)) Then
WScript.Stdout.Writeline "True"
Else
WScript.Stdout.Writeline "False"
End If
You are comparing strings, "10/11/2019" > "01/04/2019" and "10/11/2019" < "30/04/2019".
You may want to work with dates instead, or rewrite the strings to make sure a simple string comparison will work (YYYY/MM/DD)
The latter can be done this way :
dim FileEndDate : FileEndDate = "10/11/2019"
dim StartDateRange : StartDateRange = "01/04/2019"
dim EndDateRange : EndDateRange = "30/04/2019"
function ReformatDate(sInputDate)
dim aResult
aResult = Split(sInputDate, "/")
ReformatDate = aResult(2) & "/" & aResult(1) & "/" & aResult(0)
end function
FileEndDate = ReformatDate(FileEndDate)
StartDateRange = ReformatDate(StartDateRange)
EndDateRange = ReformatDate(EndDateRange)
If (FileEndDate >= StartDateRange) And (FileEndDate <= EndDateRange) Then
MsgBox "True"
Else
MsgBox "False"
End If
This outputs "False"
Note that this doesn't check the initial format of the strings. You may need to write your own check function to ensure that it won't crash.
You are comparing strings and not dates.
Let's try this: convert your date strings as date types, then compare them:
Dim myDateFormat As String = "dd/MM/yyyy"
Dim date0 As Date = Date.ParseExact(WScript.Arguments.Item(0).ToString(), myDateFormat, System.Globalization.CultureInfo.InvariantCulture)
Dim date1 As Date = Date.ParseExact(WScript.Arguments.Item(1).ToString(), myDateFormat, System.Globalization.CultureInfo.InvariantCulture)
Dim date2 As Date = Date.ParseExact(WScript.Arguments.Item(2).ToString(), myDateFormat, System.Globalization.CultureInfo.InvariantCulture)
If (date0 >= date1) And (date0 <= date2) Then
WScript.Stdout.Writeline "True"
Else
WScript.Stdout.Writeline "False"
End If
Also, using this could help avoid ulterior mistakes:
Option Strict On
Option Explicit On
Have fun!
Related
I am trying to develop a token (in this case a piece of code that runs inside a bigger VBScript) that returns information from an XML that is supplied by the 3rd-party software to a word plugin using bookmarks to provide parameters to the tokens.
So here is what is going on,
XmlDoc.SetProperty "SelectionLanguage", "XPath"
ReturnData = vbNullString
Public Function GetParameterXml()
GetParameterXml = _
"<Parameters>" & _
"<Parameter Value='Last_Hearing' Code='L' Description='Last_Hearing' Type='Combo'>" & _
"<Options>" & _
"<Option Code='' Description='True' Value='True' />" & _
"<Option Code='' Description='False' Value='False' />" & _
"</Options>" & _
"</Parameter>" & _
"</Parameters>"
End Function
Dim oNode : Set oNode = XmlDoc.SelectSingleNode("/Record/CelloXml/Integration/Case/Hearing/Setting/CourtroomMinutes/Comment")
Dim lastHearing : Set lastHearing = Parameters.Item( BookMark, "Last_Hearing" )
If IsNull(lastHearing) Then
lastHearing = False
End If
stop
If lastHearing.Value = "True" Then
Dim dateNodes : Set dateNodes = XmlDoc.SelectNodes("/Record/CelloXml/Integration/Case/Hearing/Setting/HearingDate")
Dim mostRecentHearingDate
Dim dateNode
Dim todaysDate
todaysDate = Date
Dim dateList : Set dateList = CreateObject("System.Collections.ArrayList")
For Each dateNode In dateNodes
dateList.Add CDate(dateNode.Text)
Next
dateList.Sort()
Dim tempDate
For Each tempDate In dateList
If tempDate < todaysDate Then
mostRecentHearingDate = tempDate
End If
Next
mostRecentHearingDate = CStr(mostRecentHearingDate)
Set oNode = XmlDoc.selectSingleNode("/Record/CelloXml/Integration/Case/Hearing/Setting[HearingDate/text()='" & mostRecentHearingDate & "']/CourtroomMinutes/Comment")
End If
If Not oNode Is Nothing Then
ReturnData = oNode.text
Else
ReturnData = vbNullString
End If
Everything works the way that I want it to up until
Set oNode = XmlDoc.selectSingleNode("/Record/CelloXml/Integration/Case/Hearing/Setting[HearingDate/text()='" & mostRecentHearingDate & "']/CourtroomMinutes/Comment")
I needed dateList to hold dates(or date literals) because I assumed that I would get a bad sort if I tried to sort the dates as a string rather than an actual date, so I converted the text from the node to a date(or date literal) and added it to dateList
When I was done with all the calculations then I needed a string to run in my XPath, if I hard code the date(as a string{08/05/2014}) into the XPath query it works, but when I turn mostRecentHearingDate into a string using CStr then oNode is Set to Nothing
The Node exists and holds data
So,
Why is this happening?
How do I get it to function the way I think it should?
If you do
dim mostRecentHearingDate
mostRecentHearingDate = CDate("08/05/2014")
mostRecentHearingDate = CStr(mostRecentHearingDate)
mostRecentHearingDate = "8/5/2014" not "08/05/2014" it drops the leading "0"
try
mostRecentHearingDate = Right("0"&DatePart("m",mostRecentHearingDate),2) & "/" & Right("0"&DatePart("d",mostRecentHearingDate),2) & "/" & DatePart("YYYY",mostRecentHearingDate)
That yields
08/05/2014
I have a simple problem but I can't seem to find an anwser.
I want to execute code:
if current date < 1 April then
do stuff
else
do other stuff
end if
I thought it was pretty easy, since I can get date and format it my way, but problem is when user has different Date format. I did something like this:
Private Sub UserForm_Initialize()
Dim rok As Long, rok_kontrola As Date
rok = Format(Date, "yyyy")
rok_kontrola = Format(Date, "dd-mm-yyyy")
If rok_kontrola < "01-04-" & rok Then
Me.Controls("rok1").Value = True
Else
Me.Controls("rok2").Value = True
End If
End Sub
Try this one:
If Date < DateSerial(Year(Date), 4, 1) Then
Me.Controls("rok1").Value = True
Else
Me.Controls("rok2").Value = True
End If
I am writing a macro that processes an excel with lots of data. One of the rows contains a date range like wkstartdate - wkenddate and I would like to use dateadd function to print next date range every week (like '27-01-14 - 02-02-14' in below case) but unable to do so.
'06-01-14 - 12-01-14'
'13-01-14 - 19-01-14'
'20-01-14 - 26-01-14'
I used below excerpt which fails:
Range("E" & Lastrow).Select
prwk = Split(ActiveCell.Value, "-")
'curr_wkstart = DateAdd("d", 7, prwk(1)) 'error as maybe prwk(1) isnt correct format
'curr_wkend = DateAdd("d", 7, prwk(2)) 'error
Range("E" & Lastrow + 1).Value = curr_wkstart & curr_wkend 'no result
For testing purpose I print, prwk(1) which is 20/01/14 in the above case, in a diff cell and add 7 days, which gives me 1/21/2020 instead of '27/01/14'. I also tried using Cdate function, but still error
Can you please advise??
I think what you want to use here are the Format and DateSerial functions. Here's how I came at it:
Function GetNextWeek(TheStartWeek)
a = Split(TheStartWeek, " - ")
b = Split(a(1), "-")
c = DateSerial(b(2), b(1), b(0)) + 1
d = c + 6
GetNextWeek = Format(c, "dd-mm-yy") & " - " & Format(d, "dd-mm-yy")
End Function
Sub Test()
Debug.Print GetNextWeek("13-01-14 - 19-01-14") 'Givs you "20-01-14 - 26-01-14"
End Sub
Hope this helps.
I searched but couldn't find what I'm looking for.
How do I convert a normal Date() in ASP Classic to a string in the format dd-monthname-YYYY?
Here is an example:
Old date (mm/dd/YYYY) : 5/7/2013
New date (dd-monthname-YYYY) : 7-May-2013
Dim Dt
Dt = CDate("5/7/2013")
Response.Write Day(Dt) & "-" & MonthName(Month(Dt)) & "-" & Year(Dt)
' yields 7-May-2013
' or if you actually want dd-monthname-YYYY instead of d-monthname-YYYY
Function PadLeft(Value, Digits)
PadLeft = CStr(Value)
If Len(PadLeft) < Digits Then
PadLeft = Right(String(Digits, "0") & PadLeft, Digits)
End If
End Function
Response.Write PadLeft(Day(Dt), 2) & "-" & MonthName(Month(Dt)) & "-" & Year(Dt)
'yields 07-May-2013
I wrote an ASP Classic date handling object a while back that might be of use to you. It has a .Format() method that lets you pass in format specifiers just like the Format() function from VB/VBA. If there are any parts missing, I apologize--but this should be a giant leap forward toward natural date formatting.
Private pMillisecondMatch
Function RemoveMillisecondsFromDateString(DateString) ' Handle string dates from SQL Server that have milliseconds attached
If IsEmpty(pMillisecondMatch) Then
Set pMillisecondMatch = New RegExp
pMillisecondMatch.Pattern = "\.\d\d\d$"
pMillisecondMatch.Global = False
End If
RemoveMillisecondsFromDateString = pMillisecondMatch.Replace(DateString, "")
End Function
Function DateConvert(DateValue, ValueIfError)
On Error Resume Next
If IsDate(DateValue) Then
DateConvert = CDate(DateValue)
Exit Function
ElseIf TypeName(DateValue) = "String" Then
DateValue = RemoveMillisecondsFromDateString(DateValue)
If IsDate(DateValue) Then
DateConvert = CDate(DateValue)
Exit Function
End If
End If
DateConvert = ValueIfError
End Function
Class AspDate
Private pValue
Public Default Property Get Value()
Value = pValue
End Property
Public Property Set Value(DateValue)
If TypeName(DateValue) = "AspDate" Then
pValue = DateValue.Value
Else
Err.Raise 60020, "Class AspDate: Invalid object type " & TypeName(DateValue) & " passed to Value property."
End If
End Property
Public Property Let Value(DateValue)
pValue = DateConvert(DateValue, Empty)
End Property
Public Property Get FormattedDate()
FormattedDate = Format("yyyy-mm-dd hh:nn:ss")
End Property
Public Function Format(Specifier)
Dim Char, Code, Pos, MonthFlag
Format = "": Code = ""
If IsEmpty(Value) Then
Format = "(Empty)"
End If
Pos = 0
MonthFlag = False
For Pos = 1 To Len(Specifier) + 1
Char = Mid(Specifier, Pos, 1)
If Char = Left(Code, 1) Or Code = "" Then
Code = Code & Char
Else
Format = Format & Part(Code, MonthFlag)
Code = Char
End If
Next
End Function
Private Function Part(Interval, MonthFlag)
Select Case LCase(Left(Interval, 1))
Case "y"
Select Case Len(Interval)
Case 1, 2
Part = Right(CStr(Year(Value)), 2)
Case 3, 4
Part = Right(CStr(Year(Value)), 4)
Case Else
Part = Right(CStr(Year(Value)), 4)
End Select
Case "m"
If Not MonthFlag Then ' this is a month calculation
MonthFlag = True
Select Case Len(Interval)
Case 1
Part = CStr(Month(Value))
Case 2
Part = Right("0" & CStr(Month(Value)), 2)
Case 3
Part = MonthName(Month(Value), True)
Case 4
Part = MonthName(Month(Value))
Case Else
Part = MonthName(Month(Value))
End Select
Else ' otherwise it's a minute calculation
Part = Right("0" & Minute(Value), 2)
End If
Case "n"
Part = Right("0" & Minute(Value), 2)
Case "d"
Part = CStr(Day(Value))
If Len(Part) < Len(Interval) Then
Part = Right("0" & Part, Len(Interval))
End If
Case "h"
MonthFlag = True
Part = CStr(Hour(Value))
If Len(Part) < Len(Interval) Then
Part = Right("0" & Part, Len(Interval))
End If
Case "s"
Part = Right("0" & Second(Value), 2)
Case Else ' The item is not a recognized date interval, just return the value
Part = Interval
End Select
End Function
End Class
Function NewDate(Value)
Set NewDate = New AspDate
NewDate.Value = Value
End Function
Function NewDateWithDefault(Value, DefaultValue)
Set NewDateWithDefault = New AspDate
If Value = Empty Then
NewDateWithDefault.Value = DefaultValue
Else
NewDateWithDefault.Value = Value
End If
End Function
Here's example code using the above class:
<%=NewDate(Checkin.Parameters.Item("#DOB").Value).Format("mm/dd/yyyy")%>
To get the format you've noted above, you would do:
.Format("d-mmmm-yyyy")
I need to check if the date entered in a textbox is valid. It has to be a single textbox, so no workaround this way.
Now, I have this code:
Private Sub cmdOK_Click()
Dim dataAnalisi As Date
If IsDate(txtDataAnalisi.Value) Then
dataAnalisi = txtDataAnalisi.Value
Dim giornoAnalisi, meseAnalisi As Integer
giornoAnalisi = Format(dataAnalisi, "dd")
meseAnalisi = Format(dataAnalisi, "mm")
If giornoAnalisi <= 31 And meseAnalisi <= 12 Then
Call arrayList(dataAnalisi)
Unload Me
Else
GoTo DateError
End If
Else
DateError:
MsgBox "Inserire una data formattata correttamente!", vbCritical, "Errore nell'inserimento!"
txtDataAnalisi.SetFocus
End If
End Sub
Sorry if it has text in Italian. The function works decently, the only problem is that if I input for instance 11/14/12 (where the date is dd/mm/yy and 14 was a mistype) it inverts the day and month values. Instead, I want the sub to tell the user to check his input again! Can you help me? Thank you!
There are variations of this question every month or so. I am convinced that Excel will treat a date that is a valid American date as an American date. I have thought this for many years but others disagree.
I use functions like the one below which check for formats I believe Excel will misinterpret and convert them to an unambiguous format.
I use the English abbreviations for months. I believe French is the only language that does not permit three character abbreviations for months so perhaps you have your own set. You will have to adapt that part of the routine to your requirement.
Hopes this helps.
Function MyDateValue(ByVal DateIn As String, ByRef DateOut As Date) As Boolean
' DateIn is a value to be checked as a valid date.
' If it is a valid date, DateOut is set to its value and the function
' returns True.
' Excel misinterprets dates such as "4/14/11" as 14 April 2011. This routine
' checks for such dates and, if necessary, changes them to an unambiguous
' format before calling IsDate and DateValue.
Dim DatePart() As String
Dim MonthNum As Long
Const MonthAbbr As String = "janfebmaraprmayjunjulaugsepoctnovdec"
' Replace popular delimiters with Microsoft standard
DateIn = Replace(DateIn, "-", "/")
DateIn = Replace(DateIn, "\", "/")
DatePart = Split(DateIn, "/")
If UBound(DatePart) = 2 Then
' DateStg is three values separated by delimiters
' Check middle part
If IsNumeric(DatePart(1)) Then
MonthNum = Val(DatePart(1))
If MonthNum >= 1 And MonthNum <= 12 Then
' Middle part could be numeric month
' Convert to format Excel does not misinterpret
'Debug.Assert False
DatePart(1) = Mid(MonthAbbr, ((MonthNum - 1) * 3) + 1, 3)
DateIn = Join(DatePart, "-")
If IsDate(DateIn) Then
DateOut = DateValue(DateIn)
MyDateValue = True
Exit Function
End If
Else
' Middle part cannot be a month
'Debug.Assert False
MyDateValue = False
Exit Function
End If
Else
'Debug.Assert False
' The middle part is not a number. It could be a month abbreviation
MonthNum = InStr(1, MonthAbbr, LCase(DatePart(1)))
If MonthNum = 0 Then
' The middle portion is neither a month number nor a month abbreviation
Debug.Assert False
MyDateValue = False
Else
' The middle portion is a month abbreviation.
' Excel will handle date correctly
'Debug.Assert False
MonthNum = (MonthNum - 1) / 3 + 1
DateIn = Join(DatePart, "-")
If IsDate(DateIn) Then
'Debug.Assert False
DateOut = DateValue(DateIn)
MyDateValue = True
Exit Function
End If
End If
End If
Else
' Debug.Assert False
' Use IsDate for other formats
If IsDate(DateIn) Then
' Debug.Assert False
DateOut = DateValue(DateIn)
MyDateValue = True
Exit Function
Else
' Debug.Assert False
MyDateValue = False
End If
End If
End Function