我在使用@XavierPena方法時仍然遇到問題,但我在所有情況下使用的全局方法如下;
'date can be in any form and this method worked for either US or UK locale
'this method always solve the problem of date settings e.g 9/24/2016 or 09/24/2016
Dim age as string = "07/30/2010"
'age
Try
Dim birthDate = Date.ParseExact(age.replace("/", "-"), "MM-dd-yyyy", Nothing)
Return (Math.Floor(Date.Now.Subtract(birthDate).TotalDays/365) & " yrs")
Catch ex As Exception
Try
Dim birthDate = Date.ParseExact(age.replace("/", "-"), "M-dd-yyyy", Nothing)
Return (Math.Floor(Date.Now.Subtract(birthDate).TotalDays/365) & " yrs")
Catch ex2 As Exception
Try
Dim birthDate = Date.ParseExact(age.replace("/", "-"), "M-d-yyyy", Nothing)
Return (Math.Floor(Date.Now.Subtract(birthDate).TotalDays/365) & " yrs")
Catch ex3 As Exception
Try
Dim birthDate = Date.ParseExact(age.replace("/", "-"), "MM-d-yyyy", Nothing)
Return (Math.Floor(Date.Now.Subtract(birthDate).TotalDays/365) & " yrs")
Catch ex4 As Exception
Try
Dim birthDate = Date.ParseExact(age.replace("/", "-"), "dd-MM-yyyy", Nothing)
Return (Math.Floor(Date.Now.Subtract(birthDate).TotalDays/365) & " yrs")
Catch ex5 As Exception
Try
Dim birthDate = Date.ParseExact(age.replace("/", "-"), "dd-M-yyyy", Nothing)
Return (Math.Floor(Date.Now.Subtract(birthDate).TotalDays/365) & " yrs")
Catch ex6 As Exception
Try
Dim birthDate = Date.ParseExact(age.replace("/", "-"), "d-M-yyyy", Nothing)
Return (Math.Floor(Date.Now.Subtract(birthDate).TotalDays/365) & " yrs")
Catch ex7 As Exception
Dim birthDate = Date.ParseExact(age.replace("/", "-"), "d-MM-yyyy", Nothing)
Return (Math.Floor(Date.Now.Subtract(birthDate).TotalDays/365) & " yrs")
End Try
End Try
End Try
End Try
End Try
End Try
End Try
日期從哪裏來?用戶輸入? – christophano
日期來自通過服務器輸入的數據庫,上面的日期只是爲了說明。 – Diamond
我假設(希望?)它們在數據庫中存儲爲'DateTime'?爲什麼要打擾字符串呢? – christophano