解决时间和日期问题

时间:2018-02-15 18:18:16

标签: javascript

我不明白这是如何运作的。有人可以向我解释一下吗?特别是变量名“prepand”,当我查看时,我看作“prepend”。还有什么呢?是(小时> 12)?

.ToList()

2 个答案:

答案 0 :(得分:0)

这是一个基本代码,它获取当前日期并通过操纵日期告诉您日期和时间。检查对应的行注释。

  

Prepand变量用于添加时间

的AM / PM

Read here in details about Date



var today = new Date(); //Creates a JavaScript Date instance that represents a single moment in time
var day = today.getDay(); // return the index of the day
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday  ","Thursday","Friday ","Saturday "];
    console.log("Today is : " + daylist[day] + ".");
    var hour = today.getHours();// getHours() method returns the hour for the specified date
    var minute = today.getMinutes();//getMinutes() method returns the minutes in the specified date
    var second = today.getSeconds();
    var prepand = (hour >= 12) ? " PM " : " AM ";
    hour = (hour >= 12) ? hour - 12 : hour; //? is a part of ternary operator which will check if hour >=12 or not. If >=  then prepand in PM otherwise AM

    if (hour === 0 && prepand === ' PM ') {
      if (minute === 0 && second === 0) {
        hour = 12;
        prepand = ' Noon';
      } else {
        hour = 12;
        prepand = ' PM';
      }
    }

    if (hour === 0 && prepand === ' AM ') {
      if (minute === 0 && second === 0) {
        hour = 12;
        prepand = ' Midnight';
      } else {
        hour = 12;
        prepand = ' AM';
      }
    }


    console.log("Current Time : " + hour + prepand + " : " + minute + " : " +
      second);




答案 1 :(得分:0)

var prepand = (hour >= 12)? " PM ":" AM ";

这转换为:

var prepand;
if (hour >= 12){
    prepand = "PM";
} else {
   prepand = "AM";
}

这篇文章是一个叫做三元的简写表达。在这种情况下,它用于为变量分配条件值。