开发者

format datetime from linq query into selectlist for dropdown

No coffee. Brain. Not. Functioning.

I have this linq query here:

Public Function ListAllVisitDates() As List(Of SelectListItem)
    Dim visitdates = db.SchoolVisitDates.Select(Function(t) New SelectListItem() With {.Text = t.VisitDate, .Value = t.VisitDateID}).ToList()
    Return visitdates
End Function

It returns a long date of MM dd yyyy hh:mm blah blah which I'm populating a dropdown box with. I need it to be a short date of mm/dd/yyy. help?

SOLVED

This was stupid easy. After grabbing the values and creating my list of selectlistitem I just looped through the items and formatted them before passing it into my vie开发者_StackOverfloww:

Dim _VisitDates As New List(Of SelectListItem)
    Try
        _VisitDates = articlerepo.ListAllVisitDates()
        For Each item In _VisitDates
            item.Text = FormatDateTime(item.Text, DateFormat.ShortDate)
        Next
        ViewData("VisitDates") = _VisitDates
    Catch ex As Exception
        Debug.Print(ex.Message)
    End Try


Public Function ListAllVisitDates() As List(Of SelectListItem)
    Dim visitdates = db.SchoolVisitDates.Select(Function(t) New SelectListItem() With {.Text = t.VisitDate.ToString("d"), .Value = t.VisitDateID}).ToList()
    Return visitdates
End Function

Calling ToString("d") on the DateTime will return the date formatted as d/M/yyyy (as would NickLarsen's answer).


If it is a DateTime, have you tried using .ToShortDateString()?


SOLVED

This was stupid easy. After grabbing the values and creating my list of selectlistitem I just looped through the items and formatted them before passing it into my view:

Dim _VisitDates As New List(Of SelectListItem)
Try
    _VisitDates = articlerepo.ListAllVisitDates()
    For Each item In _VisitDates
        item.Text = FormatDateTime(item.Text, DateFormat.ShortDate)
    Next
    ViewData("VisitDates") = _VisitDates
Catch ex As Exception
    Debug.Print(ex.Message)
End Try
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜