34

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

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

谁能建议我如何做到这一点?

4

14 回答 14

44

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

于 2013-08-30T15:43:15.847 回答
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;

演示

于 2013-08-30T15:58:51.740 回答
9

更新为使用更现代的 Luxon 而不是 MomentJS。

不要重新发明轮子。使用久经考验的库为您执行此操作,例如 Luxon:https ://moment.github.io/luxon/index.html

从他们的网站:

https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-toLocaleString

//=> 'Thu, Apr 20, 11:27 AM'
DateTime.local().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' });
于 2015-09-29T14:24:38.217 回答
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];
}

编辑:请参阅此处以获取工作演示。

于 2013-08-30T15:54:10.640 回答
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 对象的文档以获取更多信息

于 2013-08-30T16:02:59.787 回答
2

获取你需要的数据,并在String中组合起来;

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

签出:使用日期

于 2013-08-30T15:43:45.303 回答
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);
于 2015-01-24T01:08:25.807 回答
2
(new Date()).toLocaleString()

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

于 2020-05-01T14:36:14.113 回答
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
于 2014-11-08T06:01:56.543 回答
1

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';
  }
}
console.log("Current Time : " + hour + prepand + " : " + minute + " : " + second);

于 2016-02-22T18:23:05.413 回答
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;
    }  
于 2016-11-03T03:47:53.023 回答
0
<script>

    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 }

    var ctoday = dd + '/' + mm + '/' + yyyy+ '\t' +h+ ':' +m+ ':' +s;
    var d = new Date()
    var weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
    console.log("Today is " + weekday[d.getDay()])
    document.getElementById('time').innerHTML = '<span style="color:blue">' + weekday[d.getDay()] + ", " + ctoday + '</span>';
</script>
<div>
<span> Today is : <span id="time"> </span>
</div>
于 2017-11-02T13:01:08.323 回答
0

请求是以这种格式格式化日期:

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

我强烈建议遇到这个问题的任何人都应该使用 JavaScript 的IntlAPI 来格式化您的日期,而不是试图提出您自己喜欢的格式。

这是一个例子

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 语言环境中,我的输出是:

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

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

2020 年 9 月 30 日 17:23

为什么Intl更好?

  1. 它是本机代码,不需要字符串操作,不需要额外的框架,只是 2013 年之后任何时间的浏览器(当这个问题首次发布时)
    • 没有可下载的
    • 没有要添加的框架
    • 本机代码运行速度更快
  2. Intl根据用户的区域设置格式化日期,例如,不同国家/地区的用户希望阅读月份前的年份,将看到适当格式化的日期
于 2020-09-30T21:24:50.740 回答
0
function showTime(){
    let date = new Date();
    let h = date.getHours(); 
    let m = date.getMinutes(); 
    let s = date.getSeconds(); 
    let d = date.getDate() ;
    let month = date.getMonth()+1;
    let year = date.getFullYear(); 
    let session = "AM";
    
    if(h == 0){
        h = 12;
    }
    
    if(h > 12){
        h = h - 12;
        session = "PM";
    }
    
    h = (h < 10) ? "0" + h : h;
    m = (m < 10) ? "0" + m : m;
    s = (s < 10) ? "0" + s : s;
    d = (d < 10) ? "0" + d : d;
    
    //Adds zero when less than 10.

    month = (month < 10) ? "0" + month : month;
于 2022-02-19T09:56:11.580 回答