-1
val = "0"&now

msgbox val 'I am getting "0" in front of the 1 such as 01/16/2017 10:10:12 PM

If I changed it to

val2 = DateAdd("d",2,"0"&Now)

msgbox val2 'I am not getting "0" in front of 1.

Any idea, What did i wrong?

Shakeer Mirza
  • 5,054
  • 2
  • 18
  • 41
Din
  • 1
  • 2
  • 2
    It's a common mistake to make. When computing date values make sure you are working with a date, when you are ready to format a date to display a certain way *(zero padding etc.)* convert to a string. So perform your `DateAdd()` as normal then format it afterwards. See [Format current date and time](http://stackoverflow.com/a/22575530/692942). – user692942 Jan 17 '17 at 08:01

2 Answers2

0

I think you're going to have to build it:

' Add your required day
' ------------------------
nNowAdd = DateAdd("d", 2, Now())

' Build the date/time string from components
' with leading zeros -> Right("0" & Blah, 2)
' ------------------------------------------
val2 = Right("0" & Day(nNowAdd), 2) & "/" & _
Right("0" & Month(nNowAdd), 2) & "/" & Year(nNowAdd) & _
" " & Right("0" & Hour(nNowAdd), 2) & ":" & Right("0" & Minute(nNowAdd), 2)
BoffWx
  • 106
  • 4
-1

You don't keep formatting (creating fancy strings from underlaying data) and manipulating/computing data distinct.

' The concatenation operator & converts its operands to strings
WScript.Echo 1, TypeName(Date()), TypeName(Date() & "")
' DateAdd() converts its third argument to a date
WScript.Echo 2, DateAdd("d", 1, "0" & Date()) 
' Fails
WScript.Echo 3, DateAdd("d", 1, "BAD" & Date()) 

output:

1 Date String
2 18.01.2017
e:\misc\x.vbs(6, 1) Laufzeitfehler in Microsoft VBScript: Typenkonflikt: '[string: "BAD17.01.2017"]'

The "0" you prepend in the AddDate() call is lost in conversion; the value returned is a Date which has no idea of zero-padding.

Ekkehard.Horner
  • 38,498
  • 2
  • 45
  • 96