문제

I have a string that looks like "17th December 2012" and I want to convert it to a datetime, with a format of dd/MM/yyyy.

I have been on this link but that is the opposite of what I want to achieve.

I can do it by removing the suffix ("th" in "17th") by doing substrings and such and then converting it to datetime, but is there a direct way of achieving this?

a C# code would also do.

This is my code as of now, but it looks so ugly.. lol.

Private Function gettime(ByVal thetime As String) As DateTime        
    Dim result As DateTime
    Dim str1 As String = thetime
    Dim str2 As String = str1
    Dim ind As Integer = 0
    ind = str1.IndexOf(" ")
    str2 = str1.Substring(0, ind)
    str2 = Trim(StrReverse(str2))
    str2 = str2.Substring(2, 2)
    str2 = StrReverse(str2)
    ind = str1.IndexOf(" ")
    str1 = str2 & str1.Substring(ind)
    result = DateTime.Parse(str1)
    Return result
End Function
도움이 되었습니까?

해결책

You have the ability to add multiple format for your parse.

    Dim formats() As String = {"dd MMMM yyyy", "dd\s\t MMMM yyyy", "dd\t\h MMMM yyyy"}

    d = DateTime.ParseExact(s, formats, Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None)

다른 팁

This code works for me:

C#:

string datestring = "17th December 2012";
int indexOfFirstLetter = Regex.Match(
    datestring,
    "[a-z]",
    RegexOptions.IgnoreCase).Index;
datestring = datestring.Remove(indexOfFirstLetter, 2);
DateTime date = DateTime.Parse(datestring);

VB.Net:

Dim datestring As String = "17th December 2012"
Dim indexOfFirstLetter As Integer = Regex.Match( _
    datestring, _
    "[a-z]", _
    RegexOptions.IgnoreCase).Index
datestring = datestring.Remove(indexOfFirstLetter, 2)
Dim yourdate As DateTime = DateTime.Parse(datestring)

Have you tried something?

Try this:

Dim time As DateTime = DateTime.Parse("17th December 2012")

UPDATE

If the problem is just the ordinal, you can create a simple procedure to remove them:

Sub RemoveOrdinals(time As String) As String
  time = time.Replace("nd", "")
  time = time.Replace("rd", "")
  time = time.Replace("st", "")
  time = time.Replace("th", "")
  Return time
End Sub

and simply call it before do the DateTime conversion.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top