Codemunkeee
Codemunkeee

Reputation: 1613

Datetime Custom format - Show AM/PM as capitalized and not am / pm

I have a string which contains: 14 Dec 2011 9:45 am (take note that "AM" is not capitalized")

now I wanted to create a datetime variable with it.

I tried looking at this, but it is the opposite of what I wanted. I also tried this, but failed. What I've tried so far is this:

Dim dateNow As DateTime
Dim out As String = "14 Dec 2011 9:45 am"
dateNow = DateTime.ParseExact(out, "d MMM yyyy HH:mm tt", Nothing)

But sadly it's not working. Any idea? Thanks. VB.net Or C# code will be okay..

Upvotes: 4

Views: 10813

Answers (3)

Adil
Adil

Reputation: 148110

Your probably need single H instead of HH as the hour is single digit in the datetime string. You should have 09 has hour if you have HH for hour. Also use small h for 12 hours with AM and PM, Capital H is for 24 hours time format, like 1:28 PM would be 13:28 PM

dateNow = DateTime.ParseExact(out, "d MMM yyyy h:mm tt", Nothing)

The description abut using different options for hour shown below.

enter image description here

You can learn more about custom formats for DataTime here.

Upvotes: 9

Idle_Mind
Idle_Mind

Reputation: 39122

You can also use an array of allowed formats like this:

    Dim dateNow As DateTime
    Dim out As String = "14 Dec 2011 12:45 am"
    Dim allowedFormats() As String = {"d MMM yyyy h:mm tt", "dd MMM yyyy h:mm tt", "d MMM yyyy hh:mm tt", "dd MMM yyyy hh:mm tt"}
    dateNow = DateTime.ParseExact(out, allowedFormats, Nothing, Globalization.DateTimeStyles.None)

Upvotes: 0

Nagaraj S
Nagaraj S

Reputation: 13474

Try to give like this 14 Dec 2011 09:45 am add 0 near hour 9.

Dim dateNow As DateTime
Dim out As String = "14 Dec 2011 09:45 am"
dateNow = DateTime.ParseExact(out, "dd MMM yyyy HH:mm tt", Nothing)

check out Custom Date and Time Format Strings

Upvotes: 2

Related Questions