I’m trying to get the date 4 days older than now. Here is my code
我想把日期提前4天。这是我的代码
Sub calcdate()
Dim nDateTime, oDateTime As Date
nDateTime = Format(Now, "YYMMDD")
oDateTime = Format(DateAdd("d", -4, nDateTime), "YYMMDD")
MsgBox ("Today is " & nDateTime & " And OldDate is " & oDateTime)
End Sub
But output is ‘Today is 170604 And OldDate is 02-10-3734”
但是输出是"今天是170604,OldDate是02-10-3734 "
I Tried to do it without DateAdd
我试着不使用DateAdd
nDateTime = Format(Now, "YYMMDD")
oDateTime = nDateTime - 4
*Output is ‘Today is 170604 And OldDate is 170604’
*输出为“今天为170604,OldDate为170604”
I tried these changes
我试着这些变化
nDateTime = Format(Now, "YYMMDD")
oDateTime = DateAdd("d", -4, nDateTime)
*Output is ‘Today is 170604 And OldDate is 31-01-2367’
*输出是“今天是170604,OldDate是31-01-2367”
nDateTime = Format(Now, "YY-MM-DD")
oDateTime = Format(DateAdd("d", -4, nDateTime), "YY-MM-DD")
*Output is ‘Today is 17-06-04 And OldDate is 04-06-2013’
*输出为“今天17-06-04,OldDate 04-06-2013”
So it seems here it is subtracting years although I put “d”.
所以它看起来是减去年份虽然我写的是d。
last thing i tried:
最后我尝试:
nDateTime = Format(Now, "DD-MM-YY")
oDateTime = Format(DateAdd("d", -4, nDateTime), "DD-MM-YY")
*Output is ‘Today is 04-06-17 And OldDate is 31-05-2017’ i want this date, in format 170531, also why did it give me 2017 while i choose format YY only?
*输出是“今天是04-06-17,OldDate是31-05-2017”我想要这个日期,格式是170531,为什么给我2017,而我只选择格式YY ?
2 个解决方案
#1
1
Format creates a string so you can no longer sensibly perform calculations on it. Do your formatting afterwards instead:
格式创建一个字符串,这样您就不能对其进行合理的计算。然后进行格式化:
Dim nDateTime As Date, oDateTime As Date
nDateTime = Now
oDateTime = nDateTime - 4
MsgBox "Today is " & Format(nDateTime, "YYMMDD") & " And OldDate is " & Format(oDateTime, "YYMMDD")
Also, you need to declare the variable type for each variable so, as I've done.
同样,您需要为每个变量声明变量类型,正如我所做的。
#2
0
because Format(Now, "YYMMDD") result is string
因为格式(现在是“YYMMDD”)的结果是字符串
Dim myDate As Date
Dim nDatetime As String, oDateTime As String
myDate = Now
nDatetime = Format(myDate, "yymmdd")
oDateTime = Format(DateAdd("d", -4, myDate), "YY-MM-DD")
#1
1
Format creates a string so you can no longer sensibly perform calculations on it. Do your formatting afterwards instead:
格式创建一个字符串,这样您就不能对其进行合理的计算。然后进行格式化:
Dim nDateTime As Date, oDateTime As Date
nDateTime = Now
oDateTime = nDateTime - 4
MsgBox "Today is " & Format(nDateTime, "YYMMDD") & " And OldDate is " & Format(oDateTime, "YYMMDD")
Also, you need to declare the variable type for each variable so, as I've done.
同样,您需要为每个变量声明变量类型,正如我所做的。
#2
0
because Format(Now, "YYMMDD") result is string
因为格式(现在是“YYMMDD”)的结果是字符串
Dim myDate As Date
Dim nDatetime As String, oDateTime As String
myDate = Now
nDatetime = Format(myDate, "yymmdd")
oDateTime = Format(DateAdd("d", -4, myDate), "YY-MM-DD")