2014-02-14 49 views
1

我试图在日期/时间之前显示问候,具体取决于一天中的某个时间。如何在日期/时间内获得自定义消息?

  1. 早安
  2. 下午好
  3. 晚上好

我有消息的工作。

我还希望将日期和时间显示为“它是在日期时间”。

每当我尝试改变时间日期代码的东西,我甚至不能再显示它。

任何建议都会有所帮助。

function MakeArray(n) { 
    this.length = n; 
} 

monthNames = new MakeArray(13); 
monthNames[1] = "January"; 
monthNames[2] = "February"; 
monthNames[3] = "March"; 
monthNames[4] = "April"; 
monthNames[5] = "May"; 
monthNames[6] = "June"; 
monthNames[7] = "July"; 
monthNames[8] = "August"; 
monthNames[9] = "September"; 
monthNames[10] = "October"; 
monthNames[11] = "November"; 
monthNames[12] = "December"; 

dayNames = new MakeArray(8); 
dayNames[1] = "Sunday"; 
dayNames[2] = "Monday"; 
dayNames[3] = "Tuesday"; 
dayNames[4] = "Wednesday"; 
dayNames[5] = "Thursday"; 
dayNames[6] = "Friday"; 
dayNames[7] = "Saturday"; 

function dayPart(oneDate) { 
    var theHour = oneDate.getHours(); 

    if (theHour < 12) { 
     return "Good morning"; 
    } 

    if (theHour < 18) { 
     return "Good afternoon"; 
    } 

    return "Good evening"; 
} 

function customDateString(oneDate) { 
    var theDay = dayNames[oneDate.getDay() + 1], 
     theMonth = monthNames[oneDate.getMonth() + 1], 
     theYear = oneDate.getYear(); 

    theYear += (theYear < 100) ? 1900 : 0; 

    return theDay + ", " + theMonth + " " + oneDate.getDate() + ", " + theYear; 
} 

var today = new Date(); 

alert(dayPart(today) + "." + customDateString(today)); 

jsFiddle

+0

你不需要在你的'构造函数'中返回this;'。在JavaScript数组中,索引从'0'开始,如果你想使用任何泛型方法,那么你也应该考虑这一点。所以你的长度应该是'13'和'8',因为'0'是你稀疏阵列中的'洞'。 – Xotic750

+0

欣赏帮助。我不确定输出格式中哪里出错。我还需要在那里添加时间,但我已经达到了这一点,任何我试图做出的改变最终都会搞乱我输出的结果。这对我来说都是新鲜的,所以试图弄清楚我的变化如何影响其余部分。 – user3199950

+0

'年= +(年<100)'背后的理由是什么? 1900:0;'? – Xotic750

回答

0

试试这个为你的函数:

function customDateString(oneDate) { 
    var theDay = dayNames[oneDate.getDay() + 1] 
    var theMonth = monthNames[oneDate.getMonth() + 1] 
    var theYear = oneDate.getFullYear() 
    theYear += (theYear < 100) ? 1900 : 0 
    return 'It is ' + new Date().timeNow() + ' on ' + theMonth + " " + oneDate.getDate() + ", " + theYear + '. '; 

} 

有了这个原型:

Date.prototype.timeNow = function() { 
    return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds(); 
} 

Demo

getFullYear会返回一个四位数的年份,而不仅仅是getYear,例如,在2014年将返回14

相关问题