简体   繁体   English

将字符串转换为datetime vb.net

[英]convert string to datetime vb.net

i need to convert strings to date format. 我需要将字符串转换为日期格式。 the requirement is if current month is selected, the date should be getdate. 要求是如果选择当前月份,则日期应为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. 进入的数据是“2010年1月”,“2010年2月”等。 but it should be inserted into sql server database as 01/01/10 or 02/01/10 但它应该在01/01/10或02/01/10插入到sql server数据库中

I think the following should do the job for you: 我认为以下内容应该为您完成这项工作:

Dim theDate As DateTime = DateTime.ParseExact(input, "MMMM yyyy", CultureInfo.InvariantCulture)

The InvariantCulture makes sure that the month names can be parsed correctly. InvariantCulture确保可以正确解析月份名称。

DateTime.ParseExact应该能够帮助你在VB.Net中

DateTime.ParseExact Method (String, String, IFormatProvider) DateTime.ParseExact方法(String,String,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 Server列的类型是DateTime,那么您不需要担心格式,jut传递DateTime对象,它将起作用。

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月”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM