我试图将不同的日期格式转换为适当的SQL DateTime格式并且出错。
我有一台客户端的机器,使用以下日期格式设置," dd-mm-yyyy" (本地化是印度)
在VB.Net中使用Now()时,会向后解析月份和日期。我尝试过以下代码,但却遇到转换错误。
Dim Month As String = Nothing
Dim Year As String = Nothing
Dim Day As String = Nothing
Dim Hour As String = Nothing
Dim Minute As String = Nothing
Dim Second As String = Nothing
Dim strDate As String = Nothing
Dim Date_to_SQL_DateTime As Date
Month = DatePart(DateInterval.Month, Now()).ToString
Year = DatePart(DateInterval.Year, Now())
Day = DatePart(DateInterval.Day, Now())
Hour = DatePart(DateInterval.Hour, Now())
Minute = DatePart(DateInterval.Minute, Now())
Second = DatePart(DateInterval.Second, Now())
strDate = Month & “/” & Day & “/” & Year & “ “ & Hour & “:” & Minute & “:” & Second
Date_to_SQL_DateTime = Date.ParseExact(strDate, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture)
strDate返回
1/24/2017 23:17
我收到的错误是
String was not recognized as a valid Datetime
答案 0 :(得分:0)
请尝试以下操作。需要确保参数的格式与ParseExact
函数中指定的格式相同。
Dim Month As String = Nothing
Dim Year As String = Nothing
Dim Day As String = Nothing
Dim Hour As String = Nothing
Dim Minute As String = Nothing
Dim Second As String = Nothing
Dim strDate As String = Nothing
Dim Date_to_SQL_DateTime As Date
Month = DatePart(DateInterval.Month, Now()).ToString("00")
Year = DatePart(DateInterval.Year, Now()).ToString("0000")
Day = DatePart(DateInterval.Day, Now()).ToString("00")
Hour = DatePart(DateInterval.Hour, Now()).ToString("00")
Minute = DatePart(DateInterval.Minute, Now()).ToString("00")
Second = DatePart(DateInterval.Second, Now()).ToString("00")
strDate = Month & "/" & Day & "/" & Year & " " & Hour & ":" & Minute & ":" & Second
Date_to_SQL_DateTime = DateTime.ParseExact(strDate, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture)