将字符串转换为日期时间 [英] Convert a string to a datetime
问题描述
我正在使用 vb
框架3.5 开发 asp.net
p>
将字符串数据转换为Date
有困难我尝试使用cdate函数,
我有一个变量sdate是一个字符串变量和日期存储在其中,它以文本框为dd / mm / yyyy,现在我想将此字符串转换为Date变量,因为我需要执行操作作为添加一天或减去一天。
请指导我如何做到这一点。我在第三行出现错误,字符串未被识别为有效的DateTime
。我试图做如下,但错误来了
Dim sdate As String
Dim spenddt As Date
spenddt = Date.Parse(edate)
spenddt = consumdt.AddDays(-1)
但是我收到错误为
从字符串转换为类型日期无效。
如何从字符串中获取 Date
您应该使用 Date.ParseExact
或 Date.TryParseExact
正确格式字符串。
Dim edate =10/12/2009
Dim spenddt As Date = Date.ParseExact ed,dd / MM / yyyy,
System.Globalization.DateTimeFormatInfo.InvariantInfo)
或
Dim format()= {dd / MM / yyyy,d / M / yyyy,dd -MM-yyyy}
Dim spenddt As Date = Date.ParseExact(edate,format,
System.Globalizatio n.DateTimeFormatInfo.InvariantInfo,
Globalization.DateTimeStyles.None)
或
Dim format()= {dd / MM / yyyy,d / M / yyyy,dd-MM-yyyy}
Dim spenddt As Date
Date.TryParseExact(edate,format,
System.Globalization.DateTimeFormatInfo.InvariantInfo,
Globalization.DateTimeStyles.None,consumdt)
I am developing asp.net
site using vb
framework 3.5.
Im having difficulties converting string data into Date I tried using cdate function,
I have a variable sdate which is a string variable and date is stored in it which comes from textbox as dd/mm/yyyy now i want to convert this string into a Date variable as i need to perform the operations as Add a day or Subtract a day.
Please guide me how to go about this. i get the error on 3rd line as,String was not recognized as a valid DateTime
. I have tried to do as follows but the error comes
Dim sdate As String
Dim expenddt As Date
expenddt = Date.Parse(edate)
expenddt = expenddt.AddDays(-1)
But i get the error as
Conversion from String to type Date is not valid.
How can I get a Date
from the string?
You should have to use Date.ParseExact
or Date.TryParseExact
with correct format string.
Dim edate = "10/12/2009"
Dim expenddt As Date = Date.ParseExact(edate, "dd/MM/yyyy",
System.Globalization.DateTimeFormatInfo.InvariantInfo)
OR
Dim format() = {"dd/MM/yyyy", "d/M/yyyy", "dd-MM-yyyy"}
Dim expenddt As Date = Date.ParseExact(edate, format,
System.Globalization.DateTimeFormatInfo.InvariantInfo,
Globalization.DateTimeStyles.None)
OR
Dim format() = {"dd/MM/yyyy", "d/M/yyyy", "dd-MM-yyyy"}
Dim expenddt As Date
Date.TryParseExact(edate, format,
System.Globalization.DateTimeFormatInfo.InvariantInfo,
Globalization.DateTimeStyles.None, expenddt)
这篇关于将字符串转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!