如何用jquery打印日期和时间

时间:2013-11-23 17:02:02

标签: javascript jquery date

简单问题:如何以下面的格式显示浏览器的当前日期和时间?:

<h2>[current time, e.g. 02.32am]</h2>
<h4>[day of week, e.g. saturday]</h4>
<h3>[full date, e.g. 11 November 2013]</h3>

3 个答案:

答案 0 :(得分:5)

创建一个Javascript Date对象并显示其中的值。

var today = new Date();
// What happens next depends on whether you want UTC or locale time...
// assuming locale time in this example...
$('#time').html( today.getHours() + ':' + today.getMinutes());
$('#weekday').html(today.toDateString().substring(0,3));
$('#date').html( today.toDateString() );
<h2 id="time"></h2>
<h4 id="weekday"></h4>
<h3 id="date"></h3>

或者使用DatePicker中的JQueryUI来生成日期字符串,例如

 $('#date').html( $.datepicker.formatDate( "dd MM YY", today ) );
 $('#weekday').html( $.datepicker.formatDate( "DD", today ));

请记住加载jQueryUI来执行此操作。 Datepicker非常强大,还有许多其他有用的功能,包括语言环境处理

答案 1 :(得分:4)

试试这个:

的HTML

<h2 id="para1"></h2>
<h4 id="para2"></h4>
<h3 id="para3"></h3>

的Javascript

var date = new Date();   //Creates date object
var hours = date.getHours();   //get hour using date object
var minutes = date.getMinutes();    //get minutes using date object
var ampm = hours >= 12 ? 'pm' : 'am';  //Check wether 'am' or 'pm'

var month = date.getMonth(); //get month using date object
var day = date.getDate();    //get day using date object
var year = date.getFullYear();  //get year using date object
var dayname = date.getDay();  // get day of particular week

var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];

var week=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; 

document.getElementById("para1").innerHTML = hours+"."+minutes+ampm;
document.getElementById("para2").innerHTML = week[dayname];
document.getElementById("para3").innerHTML = day+" "+monthNames[month]+" "+year;

在此处查看演示:Demo

答案 2 :(得分:0)

var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var year = d.getFullYear();




 var Month=new Array(12);
 Month[0]="January";
 Month[1]="Feb";
 .
 .

 Month[11]="December";

 var MonthName = Month[d.getMonth()]; 

var today = year +" "+MonthName+" "+day; 

 alert(today);

var t=d.toLocaleTimeString();

document.getElementById('time').innerHTML = t;

     var weekday=new Array(7);
     weekday[0]="Sunday";
     weekday[1]="Monday";
     weekday[2]="Tuesday";
     weekday[3]="Wednesday";
     weekday[4]="Thursday";
     weekday[5]="Friday";
     weekday[6]="Saturday";

     var weekdayinfo = weekday[d.getDay()]; 

     document.getElementById('weekday').innerHTML = weekdayinfo;


   document.getElementById('date').innerHTML = today;


 <h2 id="time"></h2>
 <h4 id="weekday"></h4>
  <h3 id="date"></h3>

参考:http://www.jquery4u.com/snippets/jquery-todays-date-ddmmyyyy/