我已经创建了这个脚本,以dd/mm/yyyy的格式提前计算10天的日期:
var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = MyDate.getDate() + '/' + (MyDate.getMonth()+1) + '/' + MyDate.getFullYear();
我需要通过将这些规则添加到脚本中,使日期在日期和月份组件上以前导零出现。我好像不能让它工作。
if (MyDate.getMonth < 10)getMonth = '0' + getMonth;
and
if (MyDate.getDate <10)get.Date = '0' + getDate;
如果有人能告诉我在哪里插入这些脚本,我会非常感激。
试试这个:http://jsfiddle.net/xA5B7/
var MyDate = new Date();
var MyDateString;
MyDate.setDate(MyDate.getDate() + 20);
MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
+ ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
+ MyDate.getFullYear();
编辑:
为了解释,.slice(-2)给出了字符串的最后两个字符。
所以无论如何,我们都可以在日期或月份后加上“0”,只要求最后两个,因为这两个总是我们想要的。
所以如果MyDate.getMonth()返回9,它将是:
("0" + "9") // Giving us "09"
加上。slice(-2)就得到了最后两个字符:
("0" + "9").slice(-2)
"09"
但如果MyDate.getMonth()返回10,它将是:
("0" + "10") // Giving us "010"
所以加上.slice(-2)会得到最后两个字符,或者:
("0" + "10").slice(-2)
"10"
Number.prototype.padZero= function(len){
var s= String(this), c= '0';
len= len || 2;
while(s.length < len) s= c + s;
return s;
}
/ /使用:
(function(){
var myDate= new Date(), myDateString;
myDate.setDate(myDate.getDate()+10);
myDateString= [myDate.getDate().padZero(),
(myDate.getMonth()+1).padZero(),
myDate.getFullYear()].join('/');
alert(myDateString);
})()
/* value: (String)
09/09/2010
*/
下面的目的是提取配置,挂钩到日期。原型和应用配置。
我已经使用了一个数组来存储时间块,当我将()它作为一个Date对象时,它返回我要迭代的长度。完成后,我可以对返回值使用join。
这似乎工作得相当快:0.016毫秒
// Date protoype
Date.prototype.formatTime = function (options) {
var i = 0,
time = [],
len = time.push(this.getHours(), this.getMinutes(), this.getSeconds());
for (; i < len; i += 1) {
var tick = time[i];
time[i] = tick < 10 ? options.pad + tick : tick;
}
return time.join(options.separator);
};
// Setup output
var cfg = {
fieldClock: "#fieldClock",
options: {
pad: "0",
separator: ":",
tick: 1000
}
};
// Define functionality
function startTime() {
var clock = $(cfg.fieldClock),
now = new Date().formatTime(cfg.options);
clock.val(now);
setTimeout(startTime, cfg.options.tick);
}
// Run once
startTime();
演示:http://jsfiddle.net/tive/U4MZ3/
toISOString可以得到前导0
const currentdate = new Date();
const date = new date (date. utc (currentdate.getFullYear(), (currentdate.getMonth()),currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), currentdate.getSeconds()));
//你可以传递YY, MM, DD //op: 2018-03-01
//i have passed YY, MM, DD, HH, Min, Sec // op: 2021-06-09T12:14:27.000Z
console.log (date.toISOString ());
输出将类似于此:2021-06-09T12:14:27.000Z