user3257858
user3257858

Reputation: 13

using a substring on a C# aspx page

I'm trying to use substring in order to get a specific part of the date on my aspx masterpage. The reason i need this has to do with the template i downloaded and the css behind it. This is the code I've got:

<span><%= DateTime.Today.ToString("M").Substring(3), ((int)(DateTime.Today.ToString("M").Length) - 2) %></span>

I need to pick apart the current month so that the first 3 characters are in the first span and the rest of it is in the second span. The reason I need to subtract 2 is because it adds the day of the month afterwards.

Thank you in advance for any help.

Upvotes: 1

Views: 1150

Answers (2)

Brandon
Brandon

Reputation: 69953

First you should use the proper format string.

This will give you the month abbreviation (Jan, Feb, Mar, etc)

<%= DateTime.Today.ToString("MMM") %>

and this will give you the full month name

<%= DateTime.Today.ToString("MMMM") %>

Then you can do substrings on these instead and not worry about parsing off the day.

Something like:

// You can create the variable here, in the code behind, or just use a repeated
// call instead of assigning it a variable.
<% var month = DateTime.Today.ToString("MMMM"); %>

<%= DateTime.Today.ToString("MMM") %>

<%= month.Substring(3, month.Length - 3) %>

"MMM" should never return more than 3 characters (in en-us at least), but you could replace it with the length of the "MMM" call if you don't want to hard-code 3.

See this MSDN Custom Date and Time Formatting article.

Upvotes: 7

Justin
Justin

Reputation: 3397

You would just make two seperate code blocks:

<span><%= DateTime.Today.ToString("MMM") %>,</span> 
<span><%= DateTime.Today.ToString("dd") </span>

Upvotes: 0

Related Questions