如何使用JavaScript以特定格式显示Date对象?

The*_*ght 10 html javascript datetime date

我有一个Date对象,我想以下面的格式显示它:

var myDate = getDate();
// this format: "13 Jan 2012 11:00am";
Run Code Online (Sandbox Code Playgroud)

怎么可能呢?

谢谢,

zen*_*dka 12

使用toLocaleString()

const date = new Date();

const formattedDate = date.toLocaleString("en-GB", {
  day: "numeric",
  month: "short",
  year: "numeric",
  hour: "numeric",
  minute: "2-digit"
});

console.log(formattedDate); // '18 Jan 2020, 18:20'
Run Code Online (Sandbox Code Playgroud)


kno*_*lya 11

有一个很棒的JavaScript库可以很好地处理这个问题,只有5.5kb的缩小.

http://momentjs.com/

它看起来像这样:

moment().format('MMMM Do YYYY, h:mm:ss a'); // February 25th 2013, 9:54:04 am
moment().subtract('days', 6).calendar(); // "last Tuesday at 9:53 AM"
Run Code Online (Sandbox Code Playgroud)

您还可以String使用格式或Date对象传递日期.

var date = new Date();
moment(date); // same as calling moment() with no args

// Passing in a string date
moment("12-25-1995", "MM-DD-YYYY");
Run Code Online (Sandbox Code Playgroud)

对英语以外的语言也有很好的支持,如俄语,日语,阿拉伯语,西班牙语等.

查看文档.

  • momentjs 是一个很棒的库。然而,它现在是一个“[维护模式下的遗留项目](https://momentjs.com/docs/#/-project-status/)”。考虑使用其他库,例如 Day.js 或内置 [Date 方法](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)。 (2认同)

Geo*_*rge 10

如果您不想使用任何库:

<script type="text/javascript">

  var myDate = new Date();

  var month=new Array();
  month[0]="Jan";
  month[1]="Feb";
  month[2]="Mar";
  month[3]="Apr";
  month[4]="May";
  month[5]="Jun";
  month[6]="Jul";
  month[7]="Aug";
  month[8]="Sep";
  month[9]="Oct";
  month[10]="Nov";
  month[11]="Dec";
  var hours = myDate.getHours();
  var minutes = myDate.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12;
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ampm;
  // e.g. "13 Nov 2016 11:00pm";
  alert(myDate.getDate()+" "+month[myDate.getMonth()]+" "+myDate.getFullYear()+" "+strTime);
</script>
Run Code Online (Sandbox Code Playgroud)

  • myDate.getDay()为您提供星期几.请改用getDate().资料来源:http://www.w3schools.com/jsref/jsref_obj_date.asp (2认同)

Lin*_*iel 5

有许多可用于javascript的日期格式软件包,我在Steven Levithan的dateformat方面取得了很大的成功。

dateFormat(getDate(), "dd mmm yyyy hh:MMtt");
Run Code Online (Sandbox Code Playgroud)

编辑:如果您喜欢该样式,它还会向添加一个format方法Date.prototype

getDate().format("dd mmm yyyy hh:MMtt");
Run Code Online (Sandbox Code Playgroud)