将字符串转换为日期时间 vb.net
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2030407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert string to datetime vb.net
提问by sinae
i need to convert strings to date format. the requirement is if current month is selected, the date should be getdate. if any other month is selected then it should be first of that month. the data coming in is "January 2010", "February 2010" and so on. but it should be inserted into sql server database as 01/01/10 or 02/01/10
我需要将字符串转换为日期格式。要求是如果选择当前月份,则日期应为 getdate。如果选择了任何其他月份,则它应该是该月的第一个月。进来的数据是“January 2010”,“February 2010”等等。但它应该作为 01/01/10 或 02/01/10 插入到 sql server 数据库中
回答by Fredrik M?rk
I think the following should do the job for you:
我认为以下应该为您完成工作:
Dim theDate As DateTime = DateTime.ParseExact(input, "MMMM yyyy", CultureInfo.InvariantCulture)
The InvariantCulturemakes sure that the month names can be parsed correctly.
将InvariantCulture可确保月份名称可以被正确解析。
回答by Kyle
DateTime.ParseExactshould be able to help you out in VB.Net
DateTime.ParseExact应该能够帮助你在 VB.Net
回答by Paul Creasey
DateTime.ParseExact Method (String, String, IFormatProvider)
DateTime.ParseExact 方法(字符串、字符串、IFormatProvider)
DateTime dt = DateTime.ParseExact(dateString,formatString);
dt = (dt.Month == DateTime.Now.Month) ? DateTime.Now : dt;
If your calling this alot in a loop performance may be better if you only call DateTime.Now once and store it in a variable before comparison, since DateTime.Now is a fairly expensive operation.
如果您在循环中多次调用它,如果您只调用 DateTime.Now 一次并将其存储在比较之前的变量中,则性能可能会更好,因为 DateTime.Now 是一个相当昂贵的操作。
If the SQL server column is of type DateTime then you don't need to worry about the format, jut pass the DateTime object and it will work.
如果 SQL 服务器列的类型为 DateTime,则您无需担心格式,只需传递 DateTime 对象即可。
回答by Jojo Sardez
You could use this function:
你可以使用这个功能:
Private Function GetDate(ByVal source As String) As DateTime
Dim converted = DateTime.Parse(source)
If (converted.Year.Equals(DateTime.Now.Year) And converted.Month.Equals(DateTime.Now.Month)) Then
GetDate = DateTime.Now
Else
GetDate = converted
End If
End Function
it could analysed passed month + year values like "April 2010".
它可以分析通过的月份 + 年份值,例如“2010 年 4 月”。

