我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?


当前回答

new Date('Jun 5 2016').
  toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
  replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');

// => '2016-06-05'

其他回答

我不喜欢修改本机对象,而且我认为乘法比填充接受的解决方案的字符串更清楚。

函数yyyymmdd(dateIn) { var yyyy = dateIn.getFullYear(); var mm = dateIn.getMonth() + 1;// getMonth()是从零开始的 var dd = dateIn.getDate(); 返回String(10000 * yyyy + 100 * mm + dd);// mm和dd的前导零 } var today = new Date(); console.log(名称(今天));

小提琴:http://jsfiddle.net/gbdarren/Ew7Y4/

<pre>Date.prototype.getFromFormat = function(format) {
    var yyyy = this.getFullYear().toString();
    format = format.replace(/yyyy/g, yyyy)
    var mm = (this.getMonth()+1).toString(); 
    format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
    var dd  = this.getDate().toString();
    format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
    var hh = this.getHours().toString();
    format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
    var ii = this.getMinutes().toString();
    format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
    var ss  = this.getSeconds().toString();
    format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
    var ampm = (hh >= 12) ? "PM" : "AM";
    format = format.replace(/ampm/g, (ampm[1]?ampm:"0"+ampm[0]));
    return format;
};
var time_var = $('#899_TIME');
var myVar = setInterval(myTimer, 1000);
function myTimer() {
    var d = new Date(); 
    var date = d.getFromFormat('dd-mm-yyyy hh:ii:ss:ampm');
    time_var.text(date);

} </pre>

use the code and get the output like **26-07-2017 12:29:34:PM**

check the below link for your reference

https://parthiban037.wordpress.com/2017/07/26/date-and-time-format-in-oracle-apex-using-javascript/ 

另一种方法是使用toLocaleDateString与一个具有大端日期格式标准的地区,如瑞典,立陶宛,匈牙利,韩国,…:

date.toLocaleDateString('se')

删除分隔符(-)只是替换非数字的问题:

登录(新日期)。代表(/ / / D/g, ');

这不会像UTC日期格式那样产生潜在错误:与本地时区的日期相比,UTC日期可能相差一天。

这段代码修复了Pierre Guilbert的答案:

(10000年后依然有效)

YYYYMMDD=new Date().toISOString().slice(0,new Date().toISOString().indexOf("T")).replace(/-/g,"")

当我需要这样做时,我通常使用下面的代码。

var date = new Date($.now());
var dateString = (date.getFullYear() + '-'
    + ('0' + (date.getMonth() + 1)).slice(-2)
    + '-' + ('0' + (date.getDate())).slice(-2));
console.log(dateString); //Will print "2015-09-18" when this comment was written

为了解释,.slice(-2)给出了字符串的最后两个字符。

所以无论如何,我们都可以在日期或月份后加上“0”,只要求最后两个,因为这两个总是我们想要的。

所以如果MyDate.getMonth()返回9,它将是:

("0" + "9") // Giving us "09"

加上。slice(-2)就得到了最后两个字符:

("0" + "9").slice(-2)

"09"

但是如果date.getMonth()返回10,它将是:

("0" + "10") // Giving us "010"

所以加上.slice(-2)会得到最后两个字符,或者:

("0" + "10").slice(-2)

"10"