Does VBScript have a DateTime.TryParse equivalent?

淺唱寂寞╮ 提交于 2019-12-23 10:28:27

问题


Given a variant, does VBScript have an equivalent of C#'s DateTime.TryParse method?


回答1:


Use IsDate(stringDate) in conjunction with CDate(stringDate).

Use the IsDate() function to determine if date can be converted to a date or time.

CDate() recognizes date literals and time literals as well as some numbers that fall within the range of acceptable dates. When converting a number to a date, the whole number portion is converted to a date. Any fractional part of the number is converted to a time of day, starting at midnight.

CDate recognizes date formats according to the locale setting of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings. In addition, a long date format is not recognized if it also contains the day-of-the-week string.

The following example uses the CDate function to convert a string to a date.

MyDate = "October 19, 1962"   ' Define date.
MyShortDate = CDate(MyDate)   ' Convert to Date data type.
MyTime = "4:35:47 PM"         ' Define time.
MyShortTime = CDate(MyTime)   ' Convert to Date data type.



回答2:


IsDate("pony") ' Returns false



回答3:


I believe the challenge is to make the solution independent of local regional settings which is a pre-req in many situations.

The only way I found is to use DateSerial() since ParseExact() does not exists in vbs.

I think below code does the trick. There should be a smoother way to add the time component but I didn't find it. Of course this exact code only covers one input format, but that's all I need for now.

fixedDate = fixmydate("27-01-2016 18:00:00") 


Function fixmydate(mydate)  
    sday = cint(Mid(mydate,1,2))
    smonth = cint(Mid(mydate,4,2))
    syear = cint(Mid(mydate,7,4))

    shour = cint(Mid(mydate,12,2))
    sminute = cint(Mid(mydate,15,2))
    ssecond = cint(Mid(mydate,18,2))

    sdate = DateSerial(syear,smonth,sday)
    sdate = dateadd("h",shour,sdate)
    sdate = dateadd("n",sminute,sdate)
    sdate = dateadd("s",ssecond,sdate)


    fixmydate = sdate

End Function


来源:https://stackoverflow.com/questions/2517306/does-vbscript-have-a-datetime-tryparse-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!