简体   繁体   中英

How can I convert MMM format month to MM date in vb.net?

I need to get the number of the month from an abbreviation:

I have this :

Dim  monthname as string =  "Jun"

And I need to get this:

Dim monthnumber as integer =  6

How can I get this? thanks

You can use ParseExact to do that:

Dim  monthname as string =  "Jun"
Dim monthNumber as integer = DateTime.ParseExact(monthname , "MMM", CultureInfo.CurrentCulture).Month

Alternatively, create a dictionary:

Dim months = New Dictionary(Of String, Integer) From
{{1, "Jan"}, {2, "Feb"}}, ...

Dim monthNumber = months(monthname)

You can try to use this :

DateTime.ParseExact("Jun", "MMM", CultureInfo.InvariantCulture)

C#

var t = DateTime.ParseExact("Jun", "MMM", CultureInfo.InvariantCulture);
var monthNum = t.Month;

VB:

Dim t = DateTime.ParseExact("Jun", "MMM", CultureInfo.InvariantCulture)
Dim monthNum = t.Month

I test the code working properly. Please also import System.Globalization.

 Imports System
 Imports System.Globalization

Public Class Test
    Public Shared Sub Main()
        Dim  monthname as string =  "Jun"
        Dim monthnumber as integer = DateTime.ParseExact(monthName, "MMM", CultureIn

fo.CurrentCulture).Month 
        System.Console.WriteLine(monthnumber)
    End Sub
End Class
Sub Main()
    MonthsAndNmubers.GetMonthNumber("Jan")
End Sub

Public Class MonthsAndNmubers
    Private Shared ReadOnly monthsAndNumbers As IDictionary(Of String, Integer) = New Dictionary(Of String, Integer)() _
 From { 
        {"Jan", 1}, _
        {"Feb", 2}, _
        {"Mar", 3}, _
        {"Apr", 4}, _
        {"May", 5}, _
        {"Jun", 6}, _
        {"Jul", 7}, _
        {"Aug", 8}, _
        {"Sep", 9}, _
        {"Oct", 10}, _
        {"Nov", 11}, _
        {"Dec", 12} _
    }
    Public Shared Function GetMonthNumber(month As String) As Integer
        Dim monthNumber As Integer = 0
        monthsAndNumbers.TryGetValue(month, monthNumber)
        Return monthNumber
    End Function
End Class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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