Date function to display the date as mm/dd/yy - date

I'm trying to get the date in mm/dd/yy format using VB Script.
But I couldn't find any function to do the requirement , can some help me here please?

I like to use the .NET stringbuilder, because I can switch formats on the fly by just adapting the format specifier instead of using string manipulation:
wscript.echo CreateObject("system.text.stringbuilder").AppendFormat("{0:MM}/{0:dd}/{0:yy}", now).ToString()

A one-line alternative that doesn't require .NET:
d = Right("0" & Month(Date), 2) & "/" & Right("0" & Day(Date), 2) & "/" & Right(Year(Date), 2)

FormatDateTime function formats and returns a valid date:
FormatDateTime(date,2)

For locale independent formatting:
function mmddyyyy(input)
dim m: m = month(input)
dim d: d = day(input)
if (m < 10) then m = "0" & m
if (d < 10) then d = "0" & d
mmddyyyy = m & "/" & d & "/" & right(year(input), 2)
end function

Related

Date Range Visual Basic Script Not Working as Expected? [duplicate]

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!

How to convert seconds into hh:mm format in Power Bi?

In Power Bi, I have a table that contains Name and TimeSpent by user in seconds.
I want to convert total seconds spent by all users into duration format (hh:mm)
When I am getting seconds in hh:mm format for each user from database query, the values are coming up like these 12:63 etc. After importing these values into power bi, I tried to set its datatype to DateTime format but power bi shows an error saying that it is not a valid value. If I set the datatype of the column as string then strings dont add up.
What can be the ideal way to do it?
you can solve this in one line:
measure = FORMAT(TIME(0;0;tableNAME[your_column]);"HH:mm:ss")
You can try the following DAX:
HHMMSS =
INT(Table[TimeSpent] / 3600) & ":" &
RIGHT("0" & INT((Table[TimeSpent] - INT(Table[TimeSpent] / 3600) * 3600) / 60), 2) & ":" &
RIGHT("0" & MOD(Table[TimeSpent], 3600), 2)
Source
Had a similar question but for D:HH:MM:SS, code below if it's of use.
DurTime (meas) =
VAR vDur = <<<duration in CALCULATE(SUM(seconds)) >>>
RETURN INT(vDur/86400) & ":" & //Days
RIGHT("0" & INT(MOD(vDur/3600,24)),2) & ":" & //Hours
RIGHT("0" & INT(MOD(vDur/60,60)),2) & ":" & //Minutes
RIGHT("0" & INT(MOD(vDur,60)),2) //Seconds
DAX code:
= TIME(0,0,SUM('Table'[Timespent]))
Then click the modelling tab and choose Format - Date Time and choose the appropriate format.
That's a better formula, which I'm using in PBI:
HHMMSS = FORMAT(TIME(int(Table[TimeSpent] / 3600); int(mod(Table[TimeSpent]; 3600) / 60);int(mod(mod(Table[TimeSpent]; 3600); 60))); "HH:mm:ss")
I wanted a Power BI Measure wich is easy to read for this problem, code below if it's of use.
HH:MM =
VAR TotalDuration = SUM(tableNAME[your_column] ) //if you use a measure just leave the SUM part out
VAR TotalHours = TRUNC (TotalDuration/3600)
VAR Min_ = FORMAT(TRUNC(TotalDuration - TotalHours * 3600),"00")
RETURN
TotalHours & ":" & Min_
The solution is adopted from the top answer of this question PowerBi Duration calculation in hh:mm:ss

macro to extract dates from a weeks date range string and add 7 days to print next date range

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.

How can I convert Date() to dd-monthname-YYYY in ASP Classic?

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")

VBScript How can I Format Date?

I want the date to look like MM-DD-YYYY instead of MM/DD/YYYY.
0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
1 = vbLongDate - Returns date: weekday, monthname, year
2 = vbShortDate - Returns date: mm/dd/yy
3 = vbLongTime - Returns time: hh:mm:ss PM/AM
4 = vbShortTime - Return time: hh:mm
d=CDate("2010-02-16 13:45")
document.write(FormatDateTime(d) & "<br />")
document.write(FormatDateTime(d,1) & "<br />")
document.write(FormatDateTime(d,2) & "<br />")
document.write(FormatDateTime(d,3) & "<br />")
document.write(FormatDateTime(d,4) & "<br />")
If you want to use another format you will have to create your own function and parse Month, Year, Day, etc and put them together in your preferred format.
Function myDateFormat(myDate)
d = TwoDigits(Day(myDate))
m = TwoDigits(Month(myDate))
y = Year(myDate)
myDateFormat= m & "-" & d & "-" & y
End Function
Function TwoDigits(num)
If(Len(num)=1) Then
TwoDigits="0"&num
Else
TwoDigits=num
End If
End Function
edit: added function to format day and month as 0n if value is less than 10.
Suggest calling 'Now' only once in the function to guard against the minute, or even the day, changing during the execution of the function.
Thus:
Function timeStamp()
Dim t
t = Now
timeStamp = Year(t) & "-" & _
Right("0" & Month(t),2) & "-" & _
Right("0" & Day(t),2) & "_" & _
Right("0" & Hour(t),2) & _
Right("0" & Minute(t),2) ' '& _ Right("0" & Second(t),2)
End Function
The output of FormatDateTime depends on configuration in Regional Settings in Control Panel. So in other countries FormatDateTime(d, 2) may for example return yyyy-MM-dd.
If you want your output to be "culture invariant", use myDateFormat() from stian.net's solution. If you just don't like slashes in dates and you don't care about date format in other countries, you can just use
Replace(FormatDateTime(d,2),"/","-")
'for unique file names I use
Dim ts, logfile, thisScript
thisScript = LEFT(Wscript.ScriptName,LEN(Wscript.ScriptName)-4) ' assuming .vbs extension
ts = timeStamp
logfile = thisScript & "_" & ts
' ======
Function timeStamp()
timeStamp = Year(Now) & "-" & _
Right("0" & Month(Now),2) & "-" & _
Right("0" & Day(Now),2) & "_" & _
Right("0" & Hour(Now),2) & _
Right("0" & Minute(Now),2) ' '& _ Right("0" & Second(Now),2)
End Function
' ======
This snippet also solve this question with datePart function. I've also used the right() trick to perform a rpad(x,2,"0").
option explicit
Wscript.Echo "Today is " & myDate(now)
' date formatted as your request
Function myDate(dt)
dim d,m,y, sep
sep = "-"
' right(..) here works as rpad(x,2,"0")
d = right("0" & datePart("d",dt),2)
m = right("0" & datePart("m",dt),2)
y = datePart("yyyy",dt)
myDate= m & sep & d & sep & y
End Function
Although answer is provided I found simpler solution:
Date:
01/20/2017
By doing replace
CurrentDate = replace(date, "/", "-")
It will output:
01-20-2017
For anyone who might still need this in the future. My answer is very similar to qaweb, just a lot less intimidating. There seems to be no cool automatic simple function to formate date in VBS. So you'll have to do it manually. I took the different components of the date and concatenated them together.
Dim timeStamp
timeStamp = Month(Date)&"-"&Day(Date)&"-"&Year(Date)
run = msgbox(timeStamp)
Which will result in 11-22-2019 (depending on the current date)