在vb.net中将字符串转换为datetime的标准格式
问题描述:
string value =“15:10” 我必须将字符串值“15:10”转换为这样的“1899-12-30 15:10:00.000” 我写下面的代码是否有任何标准的日期/时间格式。在vb.net中将字符串转换为datetime的标准格式
Private Function GetCurrentTime(ByVal dtnew As String) As DateTime
Dim oaDate As DateTime
Dim timeValue As DateTime
Dim dtNow As DateTime
'Final date time to be stored in the time field
oaDate = DateTime.FromOADate(0)
dtnew = String.Concat(oaDate.Year, oaDate.Month, oaDate.Day, dtnew)
dtnew = dtnew.Replace(":", String.Empty)
dtNow = DateTime.ParseExact(dtnew, "yyyyMMddHHmm", Globalization.CultureInfo.InvariantCulture) 'Convert.ToDateTime(dtnew).ToString("HH:mm")
timeValue = dtNow 'New DateTime(oaDate.Year, oaDate.Month, oaDate.Day, dtNow.Hour, dtNow.Minute, dtNow.Second)
Return timeValue
End Function
答
一旦你有一个DateTime对象,你只需要控制它是如何的输出,当你调用它的.ToString()
方法。
有一个采用格式字符串的ToString
重载。如果你想输出是:
1899-12-30 15:10:00.000
那么你需要提供的字符串是:
"yyyy-MM-dd HH:mm:ss.fff"
而且,当你解析日期你可以在分析格式字符串中包含冒号(“yyyyMMddHH:mm”),因此您不需要该行
dtnew = dtnew.Replace(":", string.Empty)
答
如果您知道传递的字符串始终格式为“HH:mm”,则只需将这些元素替换为您将返回的DateTime即可。
Private Function GetCurrentTime(ByVal dtnew As String) As DateTime
'We get the date
Dim oaDate As DateTime = DateTime.FromOADate(0)
'We change the Hour
oaDate.Hour = dtNew.Substring(0, 2)
'We change the minutes
oaDate.Minute = dtNew.Substring(3, 2)
return oaDate
End Function
此日期的输出格式并不重要,因为您修改DateTime结构的字段。
我没有得到你需要的东西 – Raskayu
我已经更新了伫列 – John
你有像年份等其他值? – Raskayu