如何在vb.net中将MMM格式月转换为MM日期?

时间:2016-09-12 12:05:07

标签: c# asp.net vb.net date datetime

我需要从缩写中获取月份数:

我有这个:

Dim  monthname as string =  "Jun"

我需要得到这个:

Dim monthnumber as integer =  6

我怎么能得到这个?感谢

4 个答案:

答案 0 :(得分:4)

您可以使用ParseExact来执行此操作:

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

或者,创建一个字典:

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

Dim monthNumber = months(monthname)

答案 1 :(得分:1)

你可以尝试使用它:

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

答案 2 :(得分:1)

我测试代码是否正常工作。还请导入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

答案 3 :(得分:0)

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