以JavaScript / HTML获取日期/时间

时间:2017-10-23 15:35:51

标签: javascript html

因此,我正在尝试从头开始构建一个网站,以此来改进我的HTML / CSS技能,并在途中学习一些JavaScript。我有相当多的HTML / CSS背景,所以谢天谢地,这些并没有给我太多的问题 - 但JavaScript对我来说是一个未知的领域。简而言之,我正在尝试让我的目标网页显示当前的日期/时间,但是我已经在这个问题上工作了大约一个星期了,而且我在路障之后遇到了障碍。我拼凑了两个不同的脚本,这些脚本会让弗兰肯斯坦博士感到自豪 - 其中一个确实有效,但只是吐出了UTC时间标准,这个标准很丑陋但至少可用。另一个,它将解析字符串和所有爵士乐使它看起来不错(2017年10月19日星期日,2017年10月19日星期日)拒绝工作。

有人能指出我需要放入LandingPage.html的方向,或者我需要在我的.JS中修复它以使其工作吗?

这是我对JS的看法,我未经编辑的意识流评论和所有内容。 (不幸的是,当我让另一个工作时,我删除了我的DID所拥有的HTML。)

//|------ Date ------|
//Month/Date/Year for Landing Pad (And other pages).
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];          //Array for the 12 months in the Julian (that's the one we use right??) calendar, otherwise you'd just have an integer output for the month, which is all well and good when you have a standardized numerical format like 9/10/1996, wherein you read it Month/Day/Year - so September. Specifically September 10th, 1996. But in the UK that'd read October 9th, 1996 because they use  Day/Month/Year. So yeah, it's getting spelt out completely.

function getDayOfWeek(date) {         //// Accepts a Date object or date string that is recognized by the Date.parse() method.
  var dayOfWeek = new Date(date).getDay();
  return isNaN(dayOfWeek) ? null : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][dayOfWeek];
}
         //Array for the 7 days. You should know why from reading the comment on 'var months ='.
var n = new Date();         //Constructor. Without this, we'd just be looking at a string. The horror. Date() without new preceding has no arguments and will just spit out a string. Neato. 'new Date()' allows for a new 'Date' object to be created with whatever parameters. I've got word/typing satiation for the word date now.
var y = n.getFullYear();          //Variable to pull the full current year. (Wya John Oliver?)
var m = n.getMonth();         //Variable to pull the month.
var d = n.getDate();          //Variable to get the numerical date for the month.
document.getElementById("date").value = "It is" + " " + getDayOfWeek(new Date()) + ", " + months[m] + " " + d + ", " + y;         //Spits out something like October 9 2017. Sadly no ordinals, at least not today. My head hurts too much right now for that.
//|------------------|

谢谢你们!

1 个答案:

答案 0 :(得分:0)

首先,从数组中选择值的方式应该是这样的

var dayOfWeek = new Date(date).getDay();
$days =  ['Sunday', 'Monday', 'Tuesday', 'Wednesday',   'Thursday', 'Friday','Saturday']
  return isNaN(dayOfWeek) ? null :$days[dayOfWeek];
}

然后你的函数在窗口的加载事件中