Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at

  • Jesper Skjønnemand 66 posts 441 karma points c-trib
    Jun 18, 2019 @ 07:50
    Jesper Skjønnemand

    How to format time without @CurrentPage ?

    On my website I want to display office hours as e.g. 08.30 - 16.00.

    I can achieve this using

    @CurrentPage.mondayFrom.ToString("") - @CurrentPage.mondayTo.ToString("")

    However, to my understanding @CurrentPage is faux pas, and I would rather use something like

    @Model.Content.GetPropertyValue("mondayFrom") - @Model.Content.GetPropertyValue("mondayTo")

    I tried adding the ToString("") without much success. Is there a better way to do this?

  • Nik 1601 posts 7202 karma points MVP 6x c-trib
    Jun 18, 2019 @ 08:20

    Hi Jesper,

    You are very close with your approach that you are trying to be fair.

    What you need to do is explicitly tell GetPropertyValue what type it should be returning, but there is a catch to this because it can cause Razor to jump out of the c# code and into the HTML code.

    So what you can do is this:

    @(Model.Content.GetPropertyValue<DateTime>("mondayFrom").ToString("")) - @(Model.Content.GetPropertyValue<DateTime>("mondayTo").ToString(""))

    Another option is this (I'm writing this on from memory so it might have a syntax error in it):

    @string.Format("{} - {}", Model.Content.GetPropertyValue<DateTime>("mondayFrom"), Model.Content.GetPropertyValue<DateTime>("mondayTo"))


  • Jesper Skjønnemand 66 posts 441 karma points c-trib
    Jun 18, 2019 @ 08:35
    Jesper Skjønnemand

    Hi Nik

    The devil is in the detail :-)

    Your first string works nicely. I had some issues wrapping it in an @if statement, but I got this to work.

    if (Model.Content.HasValue("mondayFrom") && Model.Content.HasValue("mondayTo"))
    var fra = Model.Content.GetPropertyValue<DateTime>("mondayFrom").ToString("");
    var til = Model.Content.GetPropertyValue<DateTime>("mondayTo").ToString("");
    <li>Mandag @fra - @til</li>
Please Sign in or register to post replies

Write your reply to: