如何以2位数格式获取JavaScript的月份和日期?

sri*_*ini 303 javascript

当我们调用getMonth()getDate()date对象,我们将得到的single digit number.例如 :

因为january,它显示1,但我需要将其显示为01.怎么做?

小智 734

("0" + this.getDate()).slice(-2)
Run Code Online (Sandbox Code Playgroud)

对于日期和类似的:

("0" + (this.getMonth() + 1)).slice(-2)
Run Code Online (Sandbox Code Playgroud)

这个月.

  • 很酷,但是:`函数addZ(n){返回n <10?'0'+ n:''+ n;}`更通用一点. (84认同)
  • @dak:现在什么时候真实重要?我怀疑你每秒计算这个月数千次. (29认同)
  • 切片很聪明,但它比简单的比较慢得多:http://jsperf.com/slice-vs-comparison (7认同)
  • @Sasha Chedygov确定你可以每秒数千次计算这个月,特别是如果你正在整理 (7认同)
  • 为什么不使用 [`padStart`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart)? (4认同)
  • @ KasperHoldum -`getMonth`和`getDate`返回数字,而不是字符串.如果需要与字符串的兼容性,那么"0"+数字(n)`将完成这项工作. (2认同)
  • @SashaChedygov 除非,例如,使用 openlayers 为地图制作动画,否则您通常是对的。不过,永远不要假设。我发现 dak 的评论非常有用,因为我正好遇到了这个问题。 (2认同)

Qin*_*iso 81

如果你想要一个像"YYYY-MM-DDTHH:mm:ss"的格式,那么这可能会更快:

var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ
Run Code Online (Sandbox Code Playgroud)

或者常用的MySQL日期时间格式"YYYY-MM-DD HH:mm:ss":

var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助

  • 可以使用以下内容来处理时区偏移:var date = new Date(new Date().getTime() - new Date().getTimezoneOffset()*60*1000).toISOString().substr(0,19) .replace('T',''); (3认同)

Ser*_*lov 39

月份示例:

function getMonth(date) {
  var month = date.getMonth() + 1;
  return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}  
Run Code Online (Sandbox Code Playgroud)

您还可以Date使用此功能扩展对象:

Date.prototype.getMonthFormatted = function() {
  var month = this.getMonth() + 1;
  return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,getMonth返回0到11之间的数字,而不是1和12之间的数字. (4认同)
  • 这会返回不一致的结果.对于11月和12月,它返回一个字符串,其他月份则返回一个数字. (4认同)

Mar*_*cel 20

最好的方法是创建自己的简单格式化程序(如下所示):

getDate()返回月中的某一天(从1-31开始)
getMonth()返回月份(从0到11)< 从零开始,0 = 1月,11 = 12月
getFullYear()返回年份(4位数)< 不使用getYear()

function formatDateToString(date){
   // 01, 02, 03, ... 29, 30, 31
   var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
   // 01, 02, 03, ... 10, 11, 12
   var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
   // 1970, 1971, ... 2015, 2016, ...
   var yyyy = date.getFullYear();

   // create the format you want
   return (dd + "-" + MM + "-" + yyyy);
}
Run Code Online (Sandbox Code Playgroud)


Fer*_*ali 19

我会这样做:

var date = new Date(2000, 0, 9);
var str = new Intl.DateTimeFormat('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' }).format(date);
console.log(str); // prints "01/09/2000"
Run Code Online (Sandbox Code Playgroud)


Som*_*ter 12

为什么不使用padStart

var dt = new Date();
m = (dt.getMonth() + 1).toString().padStart(2, "0");
d = dt.getDate().toString().padStart(2, "0");

console.log(m);
console.log(d);
Run Code Online (Sandbox Code Playgroud)

即使月份或日期少于10,也将始终返回2位数字。

笔记:

  • 仅当使用babel转译js代码时,这才适用于Internet Explorer 。
  • getMonth() 将从0到11返回月份,这就是为什么在填充字符串之前在月份中添加1的原因。
  • getDate()将返回从1到31的日期,因此第7个将返回07,因此我们不需要在填充字符串之前加1。

  • 11年后,padStart是最好的答案,在互联网上很难找到它 (4认同)

小智 7

以下用于使用三元运算符转换db2日期格式,即YYYY-MM-DD

var currentDate = new Date();
var twoDigitMonth=((currentDate.getMonth()+1)>=10)? (currentDate.getMonth()+1) : '0' + (currentDate.getMonth()+1);  
var twoDigitDate=((currentDate.getDate())>=10)? (currentDate.getDate()) : '0' + (currentDate.getDate());
var createdDateTo = currentDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDate; 
alert(createdDateTo);
Run Code Online (Sandbox Code Playgroud)


ssa*_*l68 6

function monthFormated(date) {
   //If date is not passed, get current date
   if(!date)
     date = new Date();

     month = date.getMonth();

    // if month 2 digits (9+1 = 10) don't add 0 in front 
    return month < 9 ? "0" + (month+1) : month+1;
}
Run Code Online (Sandbox Code Playgroud)


Ali*_*ich 6

使用Moment.js可以这样做:

moment(new Date(2017, 1, 1)).format('DD') // day
moment(new Date(2017, 1, 1)).format('MM') // month
Run Code Online (Sandbox Code Playgroud)


Moh*_*sen 5

function monthFormated() {
  var date = new Date(),
      month = date.getMonth();
  return month+1 < 10 ? ("0" + month) : month;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

这是我的解决方案:

function leadingZero(value) {
  if (value < 10) {
    return "0" + value.toString();
  }
  return value.toString();
}

var targetDate = new Date();
targetDate.setDate(targetDate.getDate());
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateCurrent = leadingZero(mm) + "/" + leadingZero(dd) + "/" + yyyy;
Run Code Online (Sandbox Code Playgroud)


小智 5

只是另一个例子,几乎是一个班轮.

var date = new Date();
console.log( (date.getMonth() < 9 ? '0': '') + (date.getMonth()+1) );
Run Code Online (Sandbox Code Playgroud)


Cra*_*ney 5

如果可以腾出一些时间,我希望得到:

YYYYMMDD
Run Code Online (Sandbox Code Playgroud)

今天,和相处:

const dateDocumentID = new Date()
  .toISOString()
  .substr(0, 10)
  .replace(/-/g, '');
Run Code Online (Sandbox Code Playgroud)

  • 答案很简洁。对于“DD/MM/YY”,我转到“new Date().toISOString().substr(0, 10).split('-').reverse().map(x =&gt; x.substr(0) , 2)).join('/')` (2认同)

Mat*_*out 5

三元运算符解决方案

如果月份或日期小于 10,简单的三元运算符可以在数字前添加“0”(假设您需要在字符串中使用此信息)。

let month = (date.getMonth() < 10) ? "0" + date.getMonth().toString() : date.getMonth();
let day = (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate();
Run Code Online (Sandbox Code Playgroud)


小智 5

const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD
Run Code Online (Sandbox Code Playgroud)