Javascript - 如何将当前日期格式配置为dayName - dd - monthName - yyyy?

时间:2016-08-10 07:10:22

标签: javascript date

我设法使用2个数组手动创建格式 dayName - dd - monthName - yyyy ,一个用于 days [] ,另一个用于 months [] < / em>并输出消息,就像我想要格式一样。但有没有更容易和自动化的方法来做到这一点?

  

类似的东西:

var d = new Date(dayName-dd-monthName-yyyy);`
  

我的代码如下:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var d = new Date();

//Javascript starts days from 0, Sunday = 1st day of the week = days[0]
var days = ["Sunday","Monday","Tuesday","Wednesday",
"Thurday","Friday","Saturday"];
var months = ["January","February","March","April","May",
"June","July","August","September","Octomber","November","December"];

//output of the Current date in format dayName-dd-monthName-yyyy
document.getElementById('demo').innerHTML = days[d.getDay()] + " " + 
d.getDate() + " " + months[d.getMonth()] + " " + d.getFullYear();

</script>

</body>
</html>

注意:我可以在日期和月份使用非英语名称,如果在您的答案中也会出现这种情况,那将是完美的。

2 个答案:

答案 0 :(得分:3)

从我的视图中,使用您自己创建的功能。它将快速工作,而不是使用外部库。

如果你想使用js库。然后使用date.js库。

答案 1 :(得分:2)

我会推荐moment.js,这是一个简单易用的库。它支持多语言,因此无需对任何一天的名称进行硬编码。当您从毫秒转换为人类可读日期时,时区也很重要:

class CompanyTest < ActiveSupport::TestCase
  test 'foobar' do
    company = companies(:base)
    #company.stubs(:foo).returns(300)
    assert_nil(company.calculate_bar)
  end
end