如何在JavaScript中获取当前日期?


当前回答

如果您想要对日期格式进行更精细的控制,我强烈建议您查看momentjs。非常棒的图书馆-只有5KB。http://momentjs.com/

其他回答

new Date().toDateString();

结果:

“2016年2月3日星期三”

var dateTimeToday = new Date();
var dateToday = new Date(
    dateTimeToday.getFullYear(), 
    (dateTimeToday.getMonth() + 1) /*Jan = 0! */, 
    dateTimeToday.getDate(), 
    0, 
    0, 
    0, 
    0);

你可以用这个

<script>
function my_curr_date() {      
    var currentDate = new Date()
    var day = currentDate.getDate();
    var month = currentDate.getMonth() + 1;
    var year = currentDate.getFullYear();
    var my_date = month+"-"+day+"-"+year;
    document.getElementById("dateField").value=my_date;    
}
</script>

HTML是

<body onload='return my_curr_date();'>
    <input type='text' name='dateField' id='dateField' value='' />
</body>

对于任何想要这样的日期格式的人,2020年4月9日

function getDate(){
  var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

  var today = new Date();
  var dd    = String(today.getDate()).padStart(2, '0');
  var mm    = months[today.getMonth()];
  var yyyy  = today.getFullYear();

  today = dd + "-" + mm + "-" + yyyy;
  return today;
}

getDate();

试试看:

var currentDate=新日期()var day=currentDate.getDate()var month=currentDate.getMonth()+1var year=currentDate.getFullYear()document.write(“<b>”+天+“/”+月+“/“+年+”</b>”)

结果如下

15/2/2012