ND's
ND's

Reputation: 2215

standard format to convert string to datetime in vb.net

string value ="15:10" I have to convert string value "15:10" to like this "1899-12-30 15:10:00.000" i write below code is there any standard date/time format.

 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

Upvotes: 0

Views: 1176

Answers (2)

Martin Verjans
Martin Verjans

Reputation: 4796

if you know the string passed is always of format "HH:mm", you just have to replace these elements into the DateTime you will return.

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

The output format of this date does not matter, because you modify the fields of the DateTime structure.

Upvotes: 0

ChrisF
ChrisF

Reputation: 137128

Once you have a DateTime object you just need to control how it's output when you call it's .ToString() method.

There's a ToString overload that takes a format string. If you want the output to be:

1899-12-30 15:10:00.000

then the string you need to provide is:

"yyyy-MM-dd HH:mm:ss.fff"

Also, when you are parsing the date you can include the colon in the parsing format string ("yyyyMMddHH:mm") so you won't need the line

dtnew = dtnew.Replace(":", string.Empty)

Upvotes: 3

Related Questions