显示当前日期和时间

时间:2014-05-28 11:57:06

标签: c# asp.net-mvc model-view-controller

我必须在我的观点的主布局中显示当前日期和时间。

我已添加当前日期和时间

<div class="date-time">@{
@Html.Label(string.Format("{0:F}",System.DateTime.Now))
  }
 </div>

问题是需要实时更新时间。 在刷新页面之前,它不会更新。

3 个答案:

答案 0 :(得分:2)

这是我的java脚本代码

function updateClock() {

    var currentTime = new Date();

    var currentHours = currentTime.getHours();
    var currentMinutes = currentTime.getMinutes();
    var currentSeconds = currentTime.getSeconds();
    var currentDay = currentTime.getDay();
    var currentMonth = currentTime.getMonth();

    // Pad the minutes and seconds with leading zeros, if required
    currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
    currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;

    // Choose either "AM" or "PM" as appropriate
    var timeOfDay = (currentHours < 12) ? "AM" : "PM";

    // Convert the hours component to 12-hour format if needed
    currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;

    // Convert an hours component of "0" to "12"
    currentHours = (currentHours == 0) ? 12 : currentHours;

    // Compose the string for display
    var currentTimeString =  currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

    return currentTimeString;
}

布局文件......需要添加javascript文件的引用,我已经添加了包。

@Scripts.Render("~/bundles/clock")


<script>
    function DiplayClock() {
        var currentTime = updateClock();
        document.getElementById("clock").firstChild.nodeValue = currentTime;
    }
</script>

</head>

<body onload="DiplayClock(); setInterval('DiplayClock()', 1000);">

<div class="date-time">
    <span id="clock">&nbsp;</span>
 </div>
</body>

答案 1 :(得分:0)

你必须使用javascript。

首先在.js文件的开头声明一个计时器:

var objTimer;

之后,您必须在任何初始.js函数中设置超时间隔:

objTimer = setTimeout("DisplayDate()", 1000);

然后,当然,代码DisplayDate()函数;类似的东西:

function DisplayDate() {

    var objDate = new Date;
    var intDate = objDate.getDate();
    var intDay = objDate.getDay();
    var intMonth = objDate.getMonth();
    var intYear = objDate.getYear();
    var intHours = objDate.getHours();
    var intMinutes = objDate.getMinutes();
    var intSeconds = objDate.getSeconds()
    var strTimeValue = "" + intHours
    strTimeValue += ((intMinutes < 10) ? ":0" : ":") + intMinutes
    strTimeValue += ((intSeconds < 10) ? ":0" : ":") + intSeconds

    var strDate = intMonth + " " + intDate + ", " + intYear + " " + strTimeValue;

    document.getElementById('fcr_spanDateTime').innerHTML = strDate;

}

希望它有所帮助。

答案 2 :(得分:0)

一个简单的方法是:

'document.getElementById(“ date”)。innerHTML = new Date()。toDateString()'