开发者

Format date function in .NET

Is 开发者_StackOverflowthere an inbuilt .NET date formatting function to return a date in the format:

3rd April 2010

It's the "rd" bit that I cannot recollect whether there is a formatting option.

Cheers, Rob.


Don't think there's a built in way. But it's fairly easy to copy/paste one from a blog post:

Protected Function FormatPostedTimeWithDayNumberSuffix(Optional ByVal format As String = "MMMM d{0}, yyyy") As String
    Dim dateTime As DateTime = Date.Parse(Entry.PostedTime)
    If Not Null.IsNull(dateTime) Then
        Dim formatTime As String = dateTime.ToString(format)

        Dim day As Integer = dateTime.Day
        Dim dayFormat As String = String.Empty
        Select Case day
            Case 1, 21, 31
                dayFormat = "st"
            Case 2, 22
                dayFormat = "nd"
            Case 3, 23
                dayFormat = "rd"
            Case Else
                dayFormat = "th"
        End Select

        Return String.Format(formatTime, dayFormat)
    End If

    Return Entry.PostedTime
End Function


I'm afraid you have to do it yourself. In C# it would be something along these lines:

if (dt.Day == 1) strdate = dt.ToString("dd") + "st";
else if (dt.Day == 2) strdate = dt.ToString("dd") + "nd";
else if (dt.Day == 3) strdate = dt.ToString("dd") + "rd";
else if (dt.Day == 21) strdate = dt.ToString("dd") + "st";
else if (dt.Day == 22) strdate = dt.ToString("dd") + "nd";
else if (dt.Day == 23) strdate = dt.ToString("dd") + "rd";
else if (dt.Day == 31) strdate = dt.ToString("dd") + "st";
else strdate = dt.ToString("dd") + "th";


Thanks all - I suspected as much but never good idea to rely on memory. There is no inbuilt function / formatting option for this requirement so you have to roll your own.

Cheers, Rob.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜