Converting Time-Stamp String to Another Date Format in VBScript - vbscript

I have datetime stamp (MMDDYYYYHHMMSS) extracted from a file Name as
Filedate = "10212015140108"
How can I convert it into datetime format mm/dd/yyyy hh:mm:ss.
Can someone help to get it resolved?

From what I can gather from the question it looks as though the Filedate value is just a string representation of date (mmddyyyyhhnnss), with that in mind did a quick test to see if I could parse it into the format required.
There are other ways of approaching this like using a RegExp object to build up a list of matches then use those to build the output.
Worth noting that this example will only work if the structured string is always in the same order and the same number of characters.
Function ParseTimeStamp(ts)
Dim df(5), bk, ds, i
'Holds the map to show how the string breaks down, each element
'is the length of the given part of the timestamp.
bk = Array(2,2,4,2,2,2)
pos = 1
For i = 0 To UBound(bk)
df(i) = Mid(ts, pos, bk(i))
pos = pos + bk(i)
Next
'Once we have all the parts stitch them back together.
'Use the mm/dd/yyyy hh:nn:ss format
ds = df(0) & "/" & df(1) & "/" & df(2) & " " & df(3) & ":" & df(4) & ":" & df(5)
ParseTimeStamp = ds
End Function
Dim Filedate, parsedDate
Filedate = "10212015140108"
parsedDate = ParseTimeStamp(FileDate)
WScript.Echo parsedDate
Output:
10/21/2015 14:01:08

Related

BGInfo Script to change date format to YYYY-MM-DD [duplicate]

This question already has an answer here:
Format current date and time in VBScript
(1 answer)
Closed 2 months ago.
I use this code to change the date format for BGInfo but I get error code on line 3
Mismatch error 'Format" 800A000D
Dim dt, strDate
dt = Date
strDate = Format(dt, "yyyy-mm-dd")
BGInfo.BGI.Date = strDate
Research I've done doesn't seen to find a solution
I've tried this:
Dim strDate As String
strDate = Format(Now(), "yyyy/mm/dd")
BGInfo.BGI.Date = strDate
but that didn't work
BGInfo uses VBScript in it's Custom field VB Script file option. It does not support VBA, so VBA functions, such as Format cannot be used.
The Following code can be placed in the Custom field to provide a new field, that can be placed on screen, to display the date in yyyy-mm-dd format:
Echo Year(Now()) & "-" & Right("0" & Month(Now()),2) & "-" & Right("0" & Day(Now()),2)
However, this will not change the format of the existing fields, such as Boot Time.
There is no bginfo object, so the code BGInfo.BGI.Date = strDate will not work. The only way to change the date format for bginfo's built-in fields is to change the user's date format.
You can work around the issue by temporarily changing the user's date format to yyyy-mm-dd, running bginfo, and then change the date format back. Here's the code (save this to a separate file, such as RunBGInfo.vbs):
Set oWSH = CreateObject("Wscript.Shell")
sDateReg = "HKCU\Control Panel\International\sShortDate"
UserDateFormat = oWSH.RegRead(sDateReg)
oWSH.RegWrite(sDateReg),"yyyy-MM-dd"
oWSH.Run "bginfo.exe bginfo.bgi /timer:0 ",1,True
oWSH.RegWrite(sDateReg),UserDateFormat
You may also want to look at a bginfo alternative written in PowerShell (such as this one) that you can then modify and extend to meet your requirements.

Substracting one Hour from Date in ISO-8601 format using VBScript [duplicate]

I was wondering if someone could help me.
I'm very new at ASP I want to format the current date and time as follows:
yyyy-mm-dd hh:mm:ss
But all i can do is the following
Response.Write Date
Can someone help me out please.
Date formatting options are limited in Classic ASP by default, there is a function FormatDateTime() which can format your date is various ways based on the servers regional settings.
For more control over date formatting though there are built in date time functions
Year(date) - Returns a whole number representing the year. Passing Date() will give back the current year.
Month(date) - Returns a whole number between 1 and 12, inclusive, representing the month of the year. Passing Date() will return the current month of the year.
MonthName(month[, abbv]) - Returns a string indicating the specified month. Passing in Month(Date()) as the month will give back the current Month string. As suggested by #Martha
Day(date) - Returns a whole number between 1 and 31, inclusive, representing the day of the month. Passing Date() will return the current day of the month.
Hour(time) - Returns a whole number between 0 and 23, inclusive, representing the hour of the day. Passing Time() will return the current hour.
Minute(time) - Returns a whole number between 0 and 59, inclusive, representing the minute of the hour. Passing Time() will return the current minute.
Second(time) - Returns a whole number between 0 and 59, inclusive, representing the second of the minute. Passing Time() will return the current second.
IMPORTANT:
When formatting date / time values, always store the date / time value first. Also, any needed calculations (DateAdd() etc.) should be applied before attempting to format or you will get unexpected results.
The functions Month(), Day(), Hour(), Minute() and Second() all return whole numbers. Luckily there is an easy workaround that lets you pad these values quickly Right("00" & value, 2) what it does is append 00 to the front of the value then from the right take the first two characters. This ensures that all single digit values return prefixed with a 0.
Dim dd, mm, yy, hh, nn, ss
Dim datevalue, timevalue, dtsnow, dtsvalue
'Store DateTimeStamp once.
dtsnow = Now()
'Individual date components
dd = Right("00" & Day(dtsnow), 2)
mm = Right("00" & Month(dtsnow), 2)
yy = Year(dtsnow)
hh = Right("00" & Hour(dtsnow), 2)
nn = Right("00" & Minute(dtsnow), 2)
ss = Right("00" & Second(dtsnow), 2)
'Build the date string in the format yyyy-mm-dd
datevalue = yy & "-" & mm & "-" & dd
'Build the time string in the format hh:mm:ss
timevalue = hh & ":" & nn & ":" & ss
'Concatenate both together to build the timestamp yyyy-mm-dd hh:mm:ss
dtsvalue = datevalue & " " & timevalue
Call Response.Write(dtsvalue)
Note: You can build the date string in one call but decided to break it down into the three variables to make it easier to read.
How Can I Format Date
Example of Parsing a Date String (Answers provide approaches to taking a date string format and parsing it to a valid Date variable).
Format the date of the previous day format yyyymmdd with VBScript (Example of why storing date / time before performing formatting is important)
VBScript ISO8601 (Example of functions to construct an ISO 8601 compliant date string)

Finding String and Reformatting Accordingly

I've been working on a VBScript that finds all files with a specific extension, .dat, searches for a specific pattern, "Date Due:\d{8}", and shifts the string around in a specific format.
I am having two problems with the below code:
It is not reading the first line. Whenever I run the script it seems to jump immediately to the second line.
It is only using the first pattern it finds and replaces the following patterns with the first pattern in the newly formatted manner.
I hope this makes sense, it's a very specific script, but I am hoping for some help understanding the problem here.
Below is my code:
Set fso = CreateObject("Scripting.FileSystemObject")
'newtext = vbLf & "Date Due:" & sub_month & sub_day & sub_year 'the text replacing Date Due:
'the purpose of this script is to format the date after Date Due:, which is currently formatted as YYYYMMDD, to MM/DD/YYYY
'example: Date Date:20180605 should be Date Due:06/05/2018
Set re = New RegExp
re.Pattern = "(\nDate Due:\d{8})" 'Looking for line, Date Due: followed by 8 digits
Dim sub_str 'substring of date due, returns the 8 digits aka the date 12345678
Dim sub_month
Dim sub_day
Dim sub_year
Dim concat_full
re.Global = False
re.IgnoreCase = True
For Each f In fso.GetFolder("C:\Users\tgl\Desktop\TestFolder\").Files
If LCase(fso.GetExtensionName(f.Name)) = "dat" Then
text = f.OpenAsTextStream.ReadAll
sub_str = Mid(text, 10, 8) 'substring of the full line, outputs the 8 digit date
sub_month = Mid(sub_str, 5, 2) 'substring of the date, outputs the 2 digit month
sub_day = Mid(sub_str, 7, 2) 'substring of the date, outputs the 2 digit day
sub_year = Mid(sub_str, 1, 4) 'substring of the date, outputs the four digit year
newtext = vbLf & "Date Due:" & sub_month & "/" & sub_day & "/" & sub_year 'replaces the text pattern defined above and concatenates the substrings with slashes
'concat_full = (sub_month & sub_day & sub_year)
f.OpenAsTextStream(2).Write re.Replace(text, newtext)
End If
Next
EDIT: When changing re.Global to True it replaces each line with the one found pattern. It should be using each found pattern as it's own and not the first one it finds.
Make your regular expression more specific and use capturing groups for extracting the relevant submatches:
re.Pattern = "(\nDate Due:)(\d{4})(\d{2})(\d{2})"
then replace the matches like this:
re.Replace(text, "$1$4/$3/$2")
$1 through $4 in the replacement string are backreferences to the capturing groups in the pattern (i.e. they're replaced with the respective captured substring).

vbscript How do I find "-" in a string and place characters that follow in a new string?

I'm using vbscript, how do I find the hyphen character "-" in a string and place characters that follow in a new string?
Basically my computer names end with a room number
PC1-3 (room 3) , PC1-4 (room 4) etc
I'm using
Dim roomArray(2)
roomArray = Array("-1", "-2", "-3")
Dim item
For each item in roomArray
If instr(strComputerName, item)
..do something
End If
Next
but I'm getting false positives due to room -33 containing "-3" etc so if I locate "-" in the string and place the characters that follow into a string I can check against the full string rather than using instr.
Thanks for any help.
This will get all text behind the last hyphen found:
Function GetRoomNumber(strComputerName)
Dim hyphenIndex
hyphenIndex = InStrRev(strComputerName, "-")
If hyphenIndex > 0 Then
GetRoomNumber = Mid(strComputerName, hyphenIndex+1)
End If
End Function
Usage in your example will be:
Dim roomArray(2)
roomArray = Array("-1", "-2", "-3")
Dim item, index
For index = LBound(roomArray) To UBound(roomArray)
item = roomArray(index)
If ("-" & GetRoomNumber(strComputerName)) = item Then
..do something
End If
Next
Or the short version would be (without defining the function with data validation):
...
If Mid(strComputerName, InStrRev(strComputerName, "-") ) = item Then
...
You need to check if strComputerName ends with dash-roomNumber.
if Right(strComputerName,Len(item))=item Then...
You kan use right and instr to retrieve this
dim s
s = "PC1-3 (room 3)"
msgbox right(s, len(s) - instr(s,"-"))

How to Find Record Set Value is Number or String?

Original:
Using VB6
If rsCardEvent(4).Value = Str Then
TimOut = rsCardEvent(4)
Else
TimeOut = Left(TimOut, 2) & ":" & Mid(TimOut, 3, 2) & ":" & Right(TimOut, 2)
End If
Getting Type MisMatch Error.
How To Find Record Set Value is String or Number
Exactly i need
If Number means print number like Time Format (HH:MM:SS)
else
print string value
Coding Help for the above condition
Edited Version:
I'm working with an ADO.Recordset object and am trying to determine the data type of a column at run-time. I need to handle the column value differently in my code depending on its underlying data type. If the column value is a string, I want to work with the value as-is. If it is a number, I want to treat the number as an packed time and convert it to HH:MM:SS format (i.e. the number 120537 would be converted to the string "12:05:37").
Below is some example code that demonstrates what I want to achieve. However, when I run this code I get a "Type Mismatch" error:
If rsCardEvent(4).Value = Str Then
TimOut = rsCardEvent(4)
Else
TimeOut = Left(TimOut, 2) & ":" & Mid(TimOut, 3, 2) & ":" & Right(TimOut, 2)
End If
Have a look at the Visual Basic 6 function library. There are functions that can help you determine the underlying type of a value.
There are quite a few but you might find these useful:
IsNumeric
IsDate
Based on this article, if rsCardEvent is an ADO recordset, you could check the Type property. Something like this:
Select Case rsCardEvent(4).Type
Case adBSTR, adChar, adVarChar, adWChar, _
adVarWChar, adLongVarChar, adLongVarWChar
' It is a string '
Case Else
' It is not a string '
End Select
You can use the IsNumeric function available in VB6.
How about:
If TypeName(rsCardEvent(4).Value) = "String" then
http://msdn.microsoft.com/en-us/library/5422sfdf.aspx

Resources