user42348
user42348

Reputation: 4319

Date Format in .net

I am getting date as April,1,2009. I want to format the date so that the month is displayed as 4. Not only for the date given above but for whatever date is given. Can anybody give appropriate code?

Upvotes: 0

Views: 413

Answers (4)

markoo
markoo

Reputation: 738

I would also suggest using .ToString() if you are intending using the whole date after converting the month to an int

        Dim strDate As String = "April,1,2009"
        Dim [date] As DateTime = DateTime.Parse(strDate)
        Dim sDate As String = [date].ToString("M,d,yyyy")

sorry if the format is weird, but I am C# developer and used an online converter.

Upvotes: 0

kenny
kenny

Reputation: 22334

As well as thedate.Month, thedate.ToString("format string") works well. "MM" for month, and it can be combined in as you please.

Upvotes: 1

John M Gant
John M Gant

Reputation: 19308

To get just the month as an integer, you could use this.

    Dim inputDate As String = "April 1, 2009"
    Dim outputDate As Date = Date.Parse(inputDate)
    Dim month As Integer = outputDate.Month

Of course you'll want to make sure inputDate is valid. For that you can use DateTime.TryParse instead of DateTime.Parse.

Upvotes: 2

CertifiedCrazy
CertifiedCrazy

Reputation: 935

Use the ToShortDateString function of the DateTime DataType to get the String representation of a Date in the format you specified.

 date.ToShortDateString()

Here's the link to the MSDN documentation. There are a number of predefined ToString functions for the DateTime DataType to make formatting for display easier. The link also explains the Culture sensitivity of the Function.

Upvotes: 3

Related Questions