Javascript显示当前日期和时间

时间:2013-08-30 15:38:48

标签: javascript

我有以下测试脚本来显示当前日期&时间: -

document.getElementById("para1").innerHTML = formatAMPM();

function formatAMPM() {
    var date = new Date();
    var hours = date.getHours();
    var days = date.getDay(); 
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0'+minutes : minutes;
    var strTime = date + ' ' + hours + ':' + minutes + ' ' + ampm;
    return strTime;
}

将显示以下内容: -

Fri Aug 30 2013 16:36:10 GMT+0100 (GMT Standard Time) 4:36 pm

但我需要将其修改为仅显示: -

Fri Aug 30 2013 4:36 pm

任何人都可以就如何实现这一目标提出建议吗?

13 个答案:

答案 0 :(得分:32)

使用Console.Log

进行演示

// get a new date (locale machine date time)
var date = new Date();
// get the date as a string
var n = date.toDateString();
// get the time as a string
var time = date.toLocaleTimeString();

// log the date in the browser console
console.log('date:', n);
// log the time in the browser console
console.log('time:',time);

使用DIV

进行演示

// get a new date (locale machine date time)
var date = new Date();
// get the date as a string
var n = date.toDateString();
// get the time as a string
var time = date.toLocaleTimeString();

// find the html element with the id of time
// set the innerHTML of that element to the date a space the time
document.getElementById('time').innerHTML = n + ' ' + time;
<div id='time'></div>

注意:这些功能并非完全支持浏览器

跨浏览器功能

//Fri Aug 30 2013 4:36 pm
console.log(formatAMPM(new Date()));

//using your function (passing in date)
function formatAMPM(date) {
    // gets the hours
    var hours = date.getHours();
    // gets the day
    var days = date.getDay();
    // gets the month
    var minutes = date.getMinutes();
    // gets AM/PM
    var ampm = hours >= 12 ? 'pm' : 'am';
    // converts hours to 12 hour instead of 24 hour
    hours = hours % 12;
    // converts 0 (midnight) to 12
    hours = hours ? hours : 12; // the hour '0' should be '12'
    // converts minutes to have leading 0
    minutes = minutes < 10 ? '0'+ minutes : minutes;
  
    // the time string
    var time = hours + ':' + minutes + ' ' + ampm;
  
    // gets the match for the date string we want
    var match = date.toString().match(/\w{3} \w{3} \d{1,2} \d{4}/);
  
    //the result
    return match[0] + ' ' + time;
}

答案 1 :(得分:23)

试试这个:

var d = new Date(),
    minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
    hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
    ampm = d.getHours() >= 12 ? 'pm' : 'am',
    months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
    days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;

DEMO

答案 2 :(得分:8)

不要重新发明轮子。

使用http://momentjs.com/

从他们的网站:

  

多个区域设置支持

moment().format('L');    // 09/29/2015
moment().format('l');    // 9/29/2015
moment().format('LL');   // September 29, 2015
moment().format('ll');   // Sep 29, 2015
moment().format('LLL');  // September 29, 2015 4:25 PM
moment().format('lll');  // Sep 29, 2015 4:25 PM
moment().format('LLLL'); // Tuesday, September 29, 2015 4:25 PM
moment().format('llll'); // Tue, Sep 29, 2015 4:25 PM

答案 3 :(得分:3)

您可以尝试以下方法:

function formatAMPM() {
    var date = new Date();
    var currDate = date.getDate();
    var hours = date.getHours();
    var dayName = getDayName(date.getDay());
    var minutes = date.getMinutes();
    var monthName = getMonthName(date.getMonth());
    var year = date.getFullYear();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var strTime = dayName + ' ' + monthName + ' ' + currDate + ' ' + year + ' ' + hours + ':' + minutes + ' ' + ampm;
    alert(strTime);
}

function getMonthName(month) {
    var ar = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    return ar[month];
}

function getDayName(day) {
    var ar1 = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
    return ar1[day];
}

编辑:请参阅here了解正常工作。

答案 4 :(得分:2)

获取所需数据并将其合并到字符串中;

getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
getHours();
getMinutes();

退房:Working With Dates

答案 5 :(得分:2)

(function(con) {
    var oDate = new Date();
    var nHrs = oDate.getHours();
    var nMin = oDate.getMinutes();
    var nDate = oDate.getDate();
    var nMnth = oDate.getMonth();
    var nYear = oDate.getFullYear();

    con.log(nDate + ' - ' + nMnth + ' - ' + nYear);
    con.log(nHrs + ' : ' + nMin);
})(console);

这会产生如下输出:

30 - 8 - 2013
21 : 30

也许您可以在MDN上提及documentation on Date object以获取更多信息

答案 6 :(得分:2)

要返回客户端日期,您可以使用以下javascript:

var d = new Date();
var month = d.getMonth()+1;
var date = d.getDate()+"."+month+"."+d.getFullYear();
document.getElementById('date').innerHTML = date;

或在jQuery中:

var d = new Date();
var month = d.getMonth()+1;
var date = d.getDate()+"."+month+"."+d.getFullYear();
$('#date').html(date);

相当于以下PHP:

<?php date("j.n.Y"); ?>

要等同于以下PHP(即前导0&#39;):

<?php date("d.m.Y"); ?>

JavaScript的:

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

if(day < 10){
    day = "0"+d.getDate();
}

if(month < 10){
    month = "0"+eval(d.getMonth()+1);
}

var date = day+"."+month+"."+d.getFullYear();
document.getElementById('date').innerHTML = date;

jQuery的:

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

if(day < 10){
    day = "0"+d.getDate();
}

if(month < 10){
    month = "0"+eval(d.getMonth()+1);
}

var date = day+"."+month+"."+d.getFullYear();
$('#date').html(date);

答案 7 :(得分:1)

<!-- //Hide From Old Browsers



var d=new Date();
var y=d.getYear();
if (y < 1000)
 y+=1900;
var day=d.getDay();
var m=d.getMonth();
var daym=d.getDate();
if (daym<10)
 daym="0"+daym;
 var mon=new Array("January", "February", "March", "April", "May", "June", "July",  "August", "September", "October", "November", "December");
document.write("<font size='2' color='#660000'>"+mon[m]+" "+daym+", "+y+"</font>");

// End Hide -->


  Result :  November 08, 2014

答案 8 :(得分:1)

&#13;
&#13;
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour;
if (hour === 0 && prepand === ' PM ') {
  if (minute === 0 && second === 0) {
    hour = 12;
    prepand = ' Noon';
  } else {
    hour = 12;
    prepand = ' PM';
  }
}
if (hour === 0 && prepand === ' AM ') {
  if (minute === 0 && second === 0) {
    hour = 12;
    prepand = ' Midnight';
  } else {
    hour = 12;
    prepand = ' AM';
  }
}
nsole.log("Current Time : " + hour + prepand + " : " + minute + " : " + second);
&#13;
&#13;
&#13;

答案 9 :(得分:1)

var today = new Date(); 
    var dd = today.getDate(); 
    var mm = today.getMonth()+1;//January is 0! 
    var yyyy = today.getFullYear(); 
    var h = today.getHours();
       var m = today.getMinutes();
       var s = today.getSeconds();
    if(dd<10){dd='0'+dd} 
    if(mm<10){mm='0'+mm} 
    if(h<10){h='0'+h}
    if(m<10){m='0'+m} 
    if(s<10){s='0'+s}  
    onload = function(){ 
        $scope.currentTime=+dd+'/'+mm+'/'+yyyy+' '+h+':'+m+':'+s;
    }  

答案 10 :(得分:1)

(new Date()).toLocaleString()

将使用您的本地格式输出日期和时间。例如:“ 2020年5月1日,上午10:35:41”

答案 11 :(得分:0)

struct CountAllocaVisitor : public InstVisitor<CountAllocaVisitor> {
  unsigned Count;
  CountAllocaVisitor() : Count(0) {}
  void visitAllocaInst(AllocaInst &AI) { ++Count; }
};

// And this class would be used like this:
CountAllocaVisitor CAV;
CAV.visit(function);
NumAllocas = CAV.Count;

答案 12 :(得分:0)

请求将日期格式设置为以下格式:

2013年8月30日星期五4:36 pm

我强烈建议遇到此问题的任何人都应使用JavaScript的Intl API设置日期格式,而不要尝试使用自己喜欢的格式。

这是一个例子

let d = new Date();
let formatter = Intl.DateTimeFormat(
    "default", // a locale name; "default" chooses automatically
    {
        weekday: "short", 
        year: "numeric",
        month: "short",
        day: "numeric",
        hour: "numeric",
        minute: "numeric"
    }
);

console.log(formatter.format(d));

在美国语言环境中,对我的输出是:

2020年9月30日,星期三,下午5:04

墨西哥某人(es-MX)的输出为:

mié。,2020年9月30日17:23

为什么Intl更好?

  1. 这是本机代码,无需字符串操作,不需要任何额外的框架,只需使用浏览器即可自2013年之后的任何时间(首次发布此问题时)
    • 什么都没下载
    • 没有要添加的框架
    • 本机代码运行速度更快
  2. Intl格式适合用户所在地区的日期,例如其他国家/地区的用户如果希望阅读本月前的年份,则会看到格式正确的日期