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)
Related
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
Wondering if someone could help me in developing a simple user interfacing macro.
I have a set of data with the first Column (A) being dates. The date range can be an arbitrary range so could go from any start date to end date (most of the time its a 6/8 weeks). Lets say for arguments sake the date range goes from 31/12/2014 18:00 to 09/02/2015 18:00 (note date is UK format of dd/mm/yyyy). I would like the user to be asked for a start and end date range that they went - say 01/01/2015 to 31/01/2015. Once they have chosen the range the macro should delete everything BEFORE their selected date range (and shift cells up) and delete everything AFTER their selected date range. The date range is in increments of 10 minutes.
I've written some code to start off:
Public Sub DateRngInput()
Dim startDate As String
Dim endDate As String
Dim sRow As Long
Dim eRow As Long
Dim lastRow As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
startDate = Left(Worksheets("Template").Cells(1, 1), 10)
endDate = Left(Worksheets("Template").Cells(lastRow, 1), 10)
sDate = InputBox("Choose Start date (dd/mm/yyyy)" & vbNewLine & vbNewLine & "Data range starts at " & startDate)
eDate = InputBox("Choose End date (dd/mm/yyyy)" & vbNewLine & vbNewLine & "Data range ends at " & endDate)
'On Error Resume Next
sRow = Worksheets("Template").Range("$A$1:$A" & lastRow).Find(sDate, LookAt:=xlPart).Row
eRow = Worksheets("Template").Range("$A$1:$A" & lastRow).Find(eDate, SearchDirection:=xlPrevious, LookAt:=xlPart).Row
MsgBox ("Your date range is from: " & vbNewLine & sDate & " at Row " & sRow & vbNewLine & "To " & vbNewLine & eDate & " at Row " & eRow)
End Sub
The macro errors out at the following line with the Run-Time error '91':
sRow = Worksheets("Template").Range("$A$1:$A" & lastRow).Find(sDate, LookAt:=xlPart).Row
Any help would be much appreciated!
Thanks.
Say we have data like:
Notice the material is not even sorted! We wish to retain only data between 1 February 2015 and 15 February 2015.
We will loop from the bottom moving up. We delete all rows outside the date limits
Sub DateKleaner()
Dim early As Date, late As Date, N As Long
Dim dt As Date
early = DateSerial(2015, 2, 1)
late = DateSerial(2015, 2, 15)
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = N To 1 Step -1
dt = Cells(i, 1).Value
If dt > late Or dt < early Then
Cells(i, 1).EntireRow.Delete
End If
Next i
End Sub
We will be left with:
EDIT#1:
Here is some code which asks the User to supply the dates:
Sub DateKleaner()
Dim early As Date, late As Date, N As Long
Dim dt As Date
early = CDate(Application.InputBox(Prompt:="Please enter start date:", Type:=2))
late = CDate(Application.InputBox(Prompt:="Please enter end date:", Type:=2))
MsgBox early & vbCrLf & late
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = N To 1 Step -1
dt = Cells(i, 1).Value
If dt > late Or dt < early Then
Cells(i, 1).EntireRow.Delete
End If
Next i
End Sub
Naturally you would probably use your own UserForm to accomplish the same thing.
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
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 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