JavaScript显示当前日期和时间

38

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

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

有人可以提供关于如何实现这个目标的建议吗?


这个链接应该会有所帮助。http://www.webdevelopersnotes.com/tips/html/formatting_time_using_javascript.php3 - JNL
有人在这里问了类似于你的问题。链接 - Kevin Rodal
14个回答

52

使用 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;
}


这不是取决于您的区域设置吗? - mvw
@mvw 是的,这是关于时间的问题...他没有提到想要显示服务器时间而不是用户所在地区的本地时间。 - abc123
你可能需要在问题中指定并返回服务器的字符串,这样用户就无法编辑它了。 - abc123
我喜欢这种本地时间格式,但你会如何将其实现到一个div中? - MizAkita
@MizAkita 更新了答案,并提供了一个新的 jsfiddle,展示了您想要看到的内容。 - abc123

28

试一下这个:

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;

演示


4
这显示了带有上午/下午的军用时间。例如 13:13 PM - James Wierzba
现在有更好的答案。 - m.e.conroy

9

1
学会享受驾驶你的旧掀背车,不要选择新轿车,除非你买的是特斯拉S。 - computingfreak
对于React,还可以查看@Joe Lu的答案:https://dev59.com/wVsW5IYBdhLWcg3wyJp3 - Chris
无法支持Moment公司的令人反感的政治宣传。 - mrg95

4
(new Date()).toLocaleString()

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


4

这个请求是将日期格式化为以下格式:

Fri Aug 30 2013 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));

我的输出为en-US时区,结果为:

Wed, Sep 30, 2020, 5:04 PM

在墨西哥(es-MX)的用户输出为:

mié., 30 de septiembre de 2020 17:23

为什么使用Intl更好?

  1. Intl是本地代码,不需要进行字符串操作,也不需要额外安装其他框架,只需要一个2013年之后发布的浏览器即可。
    • 无需下载
    • 无需添加框架
    • 本地代码运行速度更快
  2. Intl根据用户的语言环境格式化日期,例如,在不同国家/地区,用户可能希望以年份在月份之前的方式阅读日期,这时Intl会显示适当格式的日期。

1
这些天应该被接受了。 - Michael Flores

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];
}

EDIT: Refer here for a working demo.


3
(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上关于Date对象的文档以获得更多信息。

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):
<?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);

2

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

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

查看:日期处理


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接