繁体   English   中英

显示当前日期和时间

[英]Display Current Date and Time

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

我已经添加了当前日期和时间

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

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

这是我的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>

一个简单的方法是:

'document.getElementById("date").innerHTML = new Date().toDateString()'

你必须使用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;

}

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM