I'm using VBS at my workplace and I would like to convert today's date to an integer like so:
01/02/2018 → 180201
Any ideas? I'm lost.
答案 0 :(得分:1)
You need a Year(),Month() and Day() or other Date Functions in combination with Right(), to ISO date "YYYYMMDD":
IsoDate=CStr(Year(Date)) & Right("0" & CStr(Month(Date)),2) & Right("0" & CStr(Day(Date)),2)
If you want a "YYMMDD" date format:
IsoDate= Right(CStr(Year(Date)),2) & Right("0" & CStr(Month(Date)),2) & Right("0" & CStr(Day(Date)),2)
Then you can convert the date to a number with CInt() or other Data Type Conversion Functions
IntIsoDate = Cint(IsoDate)
答案 1 :(得分:0)
You can use the Now
to get the current date & time, and the Format()
function below to format in the way you want:
Function Format(dt)
dim d, m, y
d = Right("0" & Day(dt), 2)
m = Right("0" & Month(dt), 2)
y = Right(Year(dt), 2)
Format = y & m & d
End Function
This gives you the value as a String
. You wanted it as an Integer
, but it is too big for an Integer
and if you try to convert it, it will give you an OverFlow
exception. You can convert it to Long
if you want, using the CLng()
function:
CLng(Format(Now))
答案 2 :(得分:0)
如果"固定数字"如果认真考虑,问题可能是要求格式==转换为字符串日期的问题的副本。
然后正确答案
演示:
Option Explicit
Function Date2Long(dt)
' Add checks that make sense given your specs. Delete if you know what you are doing
If VarType(dt) <> vbDate Then Err.Raise 4711, "need a Date", "Date2Long"
If Year(dt) < 2001 Then Err.Raise 4712, dt & "? - need a Date >= 2001", "Date2Long"
' ...
Date2Long = 10000 * (Year(dt) - 2000) + 100 * Month(dt) + Day(dt)
End Function
Dim dt, n, d
For Each dt In Array(#2/1/2018#, #2/2/2018#, #2/3/2018#, #1/1/2001#, #11/11/2011#, #12/31/2099#, #12/31/2100#)
n = Date2Long(dt)
d = CDbl(dt)
WScript.Echo TypeName(dt), dt, TypeName(n), n, TypeName(d), d, CStr(d = Fix(d))
Next
'WScript.Echo Date2Long("pipapo")
WScript.Echo Date2Long(#12/31/2000#)
输出(德语区域设置):
cscript 48569157.vbs
Date 01.02.2018 Long 180201 Double 43132 Wahr
Date 02.02.2018 Long 180202 Double 43133 Wahr
Date 03.02.2018 Long 180203 Double 43134 Wahr
Date 01.01.2001 Integer 10101 Double 36892 Wahr
Date 11.11.2011 Long 111111 Double 40858 Wahr
Date 31.12.2099 Long 991231 Double 73050 Wahr
Date 31.12.2100 Long 1001231 Double 73415 Wahr
E:\work\proj\soa\48569157\vbs\48569157.vbs(6, 27) 31.12.2000? - need a Date >= 2001: Date2Long