How to convert string to datetime format classic a

2019-01-29 04:00发布

I have one variable

Dim tt="2008-10-20 10:00:00.0000000"

I want to change it into date,

标签: asp-classic
5条回答
Animai°情兽
2楼-- · 2019-01-29 04:04

I believe cdate is dependent on local settings to parse the string. This is no good in many situations.

To avoid this you need to use DateSerial()

and if needed add any time components to the result separately.

查看更多
可以哭但决不认输i
3楼-- · 2019-01-29 04:13

I propose a safe solution which returns the result only if the conversion is successful:

s="2008-10-20 10:00:00.0000000"
On Error Resume Next
d=CDate(Left(s,19))
On Error Goto 0
if not IsEmpty(d) then MsgBox d

Try it for a non-valid date or non-valid format. The result will be empty.

s="2008-02-31 10:00:00"

In same contexts, it is necessary to initialize the variable collecting result of CData. I recommend to initialize it as Empty. Example below shows such case - counting valid dates in a string array:

Lines = array("2008-10-20 10:00:00.0000000", "2008-10-20 10:00:00", "", "2008-02-31", "Today", "2017-02-7")
On Error Resume Next
Count=0
for each Line in Lines
    d=Empty
    d=CDate(Line)
    if not IsEmpty(d) then Count=Count+1
next
On Error Goto 0
MsgBox "Number of valid dates is "&Count

The correct answer is 2. Without initialization we get 5 as the CDate does not do anything on error so variable keeps the value from a recent iteration in the loop.

查看更多
神经病院院长
4楼-- · 2019-01-29 04:15

If do not need your milliseconds, your could use the following:

<script type="text/vbscript">
    s="2008-10-20 10:00:00.0000000"
    arr= Split(s, ".")
    d=CDate(arr(0))
    document.write(d)
</script>
查看更多
冷血范
5楼-- · 2019-01-29 04:21

Try CDATE(tt) see http://www.w3schools.com/vbscript/func_cdate.asp. I used

vbscript cdate

as keywords at Google. There were more results.

Edit: Based on the comment below (I'm sorry for mixing up), using

FormatDateTime(date,format) 

Format contains following constants:

  • 0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
  • 1 = vbLongDate - Returns date: weekday, monthname, year
  • 2 = vbShortDate - Returns date: mm/dd/yy
  • 3 = vbLongTime - Returns time: hh:mm:ss PM/AM
  • 4 = vbShortTime - Return time: hh:mm

(copied from http://www.w3schools.com/vbscript/func_formatdatetime.asp)

查看更多
看我几分像从前
6楼-- · 2019-01-29 04:28

This link, (MS CDate page), explains that:

adate = CDate(astring)

converts a string into a date object. For there, you can format it with the FormatDateTime function

str = FormatDateTime(Date)

the FormatDateTime function is "smart" -- it will format as date and time if both are present, otherwise it will format with whichever of date or time is present.

查看更多
登录 后发表回答