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 65 posts 440 karma points c-trib
    Jun 18, 2019 @ 07:50
    Jesper Skjønnemand
    0

    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("HH.mm") - @CurrentPage.mondayTo.ToString("HH.mm")
    

    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("HH.mm") without much success. Is there a better way to do this?

  • Nik 1593 posts 7151 karma points MVP 6x c-trib
    Jun 18, 2019 @ 08:20
    Nik
    100

    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("HH.mm")) - @(Model.Content.GetPropertyValue<DateTime>("mondayTo").ToString("HH.mm"))
    

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

    @string.Format("{0:HH.mm} - {1:HH.mm}", Model.Content.GetPropertyValue<DateTime>("mondayFrom"), Model.Content.GetPropertyValue<DateTime>("mondayTo"))
    

    Nik

  • Jesper Skjønnemand 65 posts 440 karma points c-trib
    Jun 18, 2019 @ 08:35
    Jesper Skjønnemand
    1

    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("HH.mm");
    var til = Model.Content.GetPropertyValue<DateTime>("mondayTo").ToString("HH.mm");
    <li>Mandag @fra - @til</li>
    }
    }
    
Please Sign in or register to post replies

Write your reply to:

Draft