在C#aspx页面上使用子字符串

1 c# asp.net substring

我正在尝试使用子字符串,以便在我的aspx母版页上获取日期的特定部分.我需要这个的原因与我下载的模板和它背后的CSS有关.这是我得到的代码:

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

我需要选择当前月份,以便前3个字符位于第一个跨度中,其余字符位于第二个跨度中.我需要减去2的原因是因为它增加了之后一个月的日期.

预先感谢您的任何帮助.

Bra*_*don 7

首先,您应该使用正确的格式字符串.

这将给你月份缩写(Jan,Feb,Mar等)

<%= DateTime.Today.ToString("MMM") %>
Run Code Online (Sandbox Code Playgroud)

这将为您提供完整的月份名称

<%= DateTime.Today.ToString("MMMM") %>
Run Code Online (Sandbox Code Playgroud)

然后你可以在这些上做子串,而不用担心解析当天.

就像是:

// 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) %>
Run Code Online (Sandbox Code Playgroud)

"MMM"不应该返回超过3个字符(至少在en-us中),但如果您不想硬编码3,则可以用"MMM"调用的长度替换它.

请参阅此MSDN 自定义日期和时间格式文章.