我要从数据库中提取日期“ ddMMyyyy”,然后将其转换为MM-dd-yyyy”,然后再显示输出。由于某些原因,有些日期仅包含7位数字,默认情况下必须为8位数字。
当系统发现日期中的数字少于8个字符时,它会引发转换日期的错误,作为一种选择,我想在显示输出的当天添加0。例如08-12-1983,默认情况下来自数据库8-12-1983
我想在显示输出的那一天加0。
我使用vb.net和sql命令。
这是我的代码。
Public BGC1, BGC2, BGC3, BGC4 As String
Public str As String
Public Sub GetBGC()
Try
myConnection.Open()
'Main.PresStartResults.Text = "Prestart Checks : "
'Main.BGCName.Text = "Employee Name "
'Main.BGCDOB.Text = "DOB"
'Dim str As String
str = "SELECT * FROM tblEmp WHERE (EmpID = '" & ADS.UserEmpID & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
Dim stringinp = dr("DOB").ToString
Dim DateTime1 = DateTime.ParseExact(stringinp, "ddMMyyyy", System.Globalization.CultureInfo.InvariantCulture)
Dim outp = DateTime1.ToString("MM-dd-yyyy")
BGC3 = outp
End While
Catch ex As Exception
MsgBox("Unable to Connect to BGC DB. You may not have access or DB not available." & ex.ToString)
End Try
myConnection.Close()
答案 0 :(得分:0)
Imports System
Imports System.Globalization
Public Module Module1
Public Sub Main()
Dim dateValue as DateTime
Dim stringinp as String
stringinp = "8-12-1983"
Dim formats = New String(){"dd-MM-yyyy", "d-MM-yyyy", "MM-dd-yyyy"}
For Each format as String in formats
If DateTime.TryParseExact(stringinp, formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, dateValue)
Exit For
End If
Next
Console.WriteLine(dateValue)
End Sub
End Module
答案 1 :(得分:0)
您可以使用PadLeft
方法,如下所示:
Dim stringinp = dr("DOB").ToString().PadLeft(8, "0")
它将在字符串的开头附加零,直到字符串的长度等于8。
答案 2 :(得分:0)
尝试
str = "SELECT * FROM tblEmp WHERE (EmpID = '" & ADS.UserEmpID & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
dim mydate as Date = dr("DOB")
Dim outp = mydate.tostring("M/dd/yyyy")
BGC3 = outp
End While
或
Dim outp = mydate.tostring("MM/dd/yyyy")