【问题标题】:How to get month as integer in Visual Basic Script?如何在 Visual Basic 脚本中将月份作为整数?
【发布时间】:2013-04-21 12:49:04
【问题描述】:

我正在尝试将当前月份作为 Visual Basic 脚本中的短字符串:

Dim month
Dim mth

month = Now.Month    ' This doesn't work.
month = Now().Month  ' Tried this too.
month = Month(Now)   ' Also tried this.

mth = MonthName(month, True)  ' (e.g. "Apr" or "Mar")

但是,我不断收到运行时错误:

Microsoft VBScript runtime error: Object required: 'Now'
Microsoft VBScript runtime error: Object required: 'Now()'
Microsoft VBScript runtime error: Type mismatch 'Month'

我可以将Now 用作字符串:

CStr(Now)

或者作为一个普通值

Dim val
val = Now

如何使用Now 作为对象来访问其成员函数?也许我将 Visual Basic 功能与 VB 脚本混淆了?

【问题讨论】:

    标签: date vbscript monthcalendar


    【解决方案1】:

    VBScript 日期不是对象 - 使用 Month(SomeDate) 函数获取 SomeDate 的月份number

    >> WScript.Echo Month(Now)
    >>
    4
    

    要获取月份的名称(缩写或完整),请使用:

    >> WScript.Echo MonthName(Month(Now()),False)
    >> WScript.Echo MonthName(Month(Now()),True)
    >>
    April
    Apr
    

    (从@collapsar 窃取,但使用了第二个参数的正确(布尔)类型)。

    官方文档 月():here MonthName():here

    [给出的示例是“活”代码,如果出现错误,则应归咎于您的代码]

    【讨论】:

    • 这也得到That also gets Microsoft VBScript runtime error: Type mismatch 'Month'
    • 您是否必须以某种方式包含Month 的定义?
    【解决方案2】:

    试试这行代码:

    MonthName(Month(Now()),1)
    

    独立解决方案:

    Dim imonth
    Dim mth
    
    imonth = Month(Now())   ' Also tried this.
    
    mth = MonthName(Month(Now()))
    
    WScript.Echo "mth = " & mth
    WScript.Echo "mth_short = )" & MonthName(Month(Now()),1)
    

    【讨论】:

    • 这也得到Microsoft VBScript runtime error: Type mismatch 'Month'
    • 如何执行代码? cscript //nologo <filename> 对我很有效(windows scripting host 5.8 on win7)
    • cscript.exe MyCode.vbs SomeArg 在 Windows 7 上来自批处理文件 (.bat)。
    • 看来您必须将变量名称month 更改为与内置函数不冲突的名称,例如。 imonth
    • 所以不区分大小写?
    【解决方案3】:

    问题是 Visual Basic 脚本不区分大小写,我的变量 month 与内置的 Month 发生冲突。

    【讨论】:

    • 我想这可以追溯到不区分大小写的原始基本实现。
    【解决方案4】:

    如给定的herehere

    语法:

    Month(Now)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-08
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多