代码之家  ›  专栏  ›  技术社区  ›  Bharat

以角度4.3运行时钟

  •  0
  • Bharat  · 技术社区  · 8 年前

    我想在我的Angular 4.3应用程序上运行时钟(数字)。

    我尝试了很多R&但是没有成功。

    所以我尝试添加基于java脚本的解决方案,但它也不起作用。

    见以下代码。

    startTime() {    
      var today = new Date();
      var h = today.getHours();
      var m = today.getMinutes();
      var s = today.getSeconds();
      m = this.checkTime(m);
      s = this.checkTime(s);   
    
      var t = setTimeout(this.startTime, 500);
      this.clock = commonSetting.formatedDate(h + ":" + m + ":" + s); // this is the variable that I am showing on the front end.    
    }
    
    checkTime(i) {
      if (i < 10) { i = "0" + i };  // add zero in front of numbers < 10
      return i;
    }
    

    有人能帮我吗?

    2 回复  |  直到 8 年前
        1
  •  4
  •   Bharat    8 年前

    现在,我的实际场景有下拉菜单,在每个下拉菜单更改事件中,我必须启动新的时钟,并且必须停止前一个时钟。

    然后,我遵循JB Nizet的注释,并使用以下代码实现了运行时钟。

    TypeScript代码

    在导出类中定义了一个全局日期变量。

    time: Date;
    

    然后在“更改方法”下拉列表中,我添加了我的解决方案。

    //get current date time, you can set your own Date() over here
    var stationdate = new Date(date_from_dropdown_change);
    
    //clear Interval, it's my system requirement
    if(this.prevNowPlaying) {
        clearInterval(this.prevNowPlaying);
    }
    
    // set clock and Interval
    this.prevNowPlaying  = setInterval(() => {         
        stationdate = new Date(stationdate.setSeconds(stationdate.getSeconds() + 1));
        this.time = stationdate;
    }, 1000);
    

    这时间

    Html

    <p class="localtime_p">{{ time | date:'MMM dd,yyyy HH:mm:ss'}}</p>
    

    目前,当我发布这个答案时,它运行良好。。

        2
  •  2
  •   joshrathke    8 年前

    Moment.js 并在 constructor() clock 属性。然后可以相应地在整个组件中显示时钟特性。

    组成部分

    constructor() {
        // Runs the enclosed function on a set interval.
        setInterval(() => {
            this.clock = moment().format('MMMM Do YYYY, h:mm:ss a');
        }, 1000) // Updates the time every second.
    }
    

    或者,您可以将基本时间戳保存到组件中的属性,然后在前端使用管道,如 Angular2-moment . 我可能会走这条路,因为它为时钟属性提供了更大的灵活性,可以在其他地方重用它,而不会过多地混淆格式。

    {{ clock | amLocale:'en' | amDateFormat:'MMMM Do YYYY, h:mm:ss a' }}
    
    推荐文章