Javascript将前导零添加到日期
我创建此脚本是为了以dd/mm/yyyy的格式提前10天计算日期:Javascript将前导零添加到日期,javascript,date,date-format,time-format,leading-zero,Javascript,Date,Date Format,Time Format,Leading Zero,我创建此脚本是为了以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(); 我需要通过将这些规则添加到脚本中,使日期在day和month
var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = MyDate.getDate() + '/' + (MyDate.getMonth()+1) + '/' + MyDate.getFullYear();
我需要通过将这些规则添加到脚本中,使日期在day和month组件上以前导零显示。我似乎无法让它工作
if (MyDate.getMonth < 10)getMonth = '0' + getMonth;
if(MyDate.getMonth<10)getMonth='0'+getMonth;
及
if(MyDate.getDate尝试以下操作:
编辑:
为了进行解释,.slice(-2)
给出了字符串的最后两个字符
因此,无论怎样,我们都可以将“0”
添加到日或月,只需请求最后两个,因为这两个始终是我们想要的
因此,如果MyDate.getMonth()
返回9
,它将是:
("0" + "9") // Giving us "09"
("0" + "10") // Giving us "010"
因此,在上面添加.slice(-2)
,将得到最后两个字符,即:
("0" + "9").slice(-2)
"09"
但是如果MyDate.getMonth()
返回10
,则它将是:
("0" + "9") // Giving us "09"
("0" + "10") // Giving us "010"
因此,添加.slice(-2)
可以得到最后两个字符,或者:
("0" + "10").slice(-2)
"10"
var MyDate=新日期();
var MyDateString='';
MyDate.setDate(MyDate.getDate());
var tempoMonth=(MyDate.getMonth()+1);
var tempoDate=(MyDate.getDate());
如果(tempoMonth<10)tempoMonth='0'+tempoMonth;
如果(节拍<10)节拍='0'+节拍;
MyDateString=tempoDate+'/'+tempoMonth+'/'+MyDate.getFullYear();
以下是Mozilla开发者网络上使用自定义“pad”函数的示例,无需扩展Javascript的数字原型
function pad(n){return n<10 ? '0'+n : n}
function pad(n){返回nfunction formatDate(jsDate){
//当天数或月份小于10时,将前导零添加到jsDate。。
//即。
//形成日期(新日期(“2013年1月3日”);
//返回
// "01/03/2103"
////////////////////
return(jsDate.getDate()下面的目标是提取配置,钩住Date.prototype
并应用配置
我使用了一个数组
来存储时间块,当我将push()
这个
作为日期
对象时,它会返回要迭代的长度。当我完成后,我可以在返回
值上使用连接
这似乎工作得很快:0.016ms
// 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();
//日期原型
Date.prototype.formatTime=函数(选项){
var i=0,
时间=[],
len=time.push(this.getHours()、this.getMinutes()、this.getSeconds());
对于(;i
演示:您可以使用三元运算符将日期格式化为“if”语句
例如:
var MyDate = new Date();
MyDate.setDate(MyDate.getDate()+10);
var MyDateString = (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate()) + '/' + ((d.getMonth()+1) < 10 ? '0' + (d.getMonth()+1) : (d.getMonth()+1)) + '/' + MyDate.getFullYear();
var MyDate=新日期();
MyDate.setDate(MyDate.getDate()+10);
var MyDateString=(MyDate.getDate()<10?'0'+MyDate.getDate():MyDate.getDate())+'/'+((d.getMonth()+1)<10?'0'+(d.getMonth()+1):(d.getMonth()+1))+'/'+MyDate.getFullYear();
所以
(MyDate.getDate()<10?'0'+MyDate.getDate():MyDate.getDate())
类似于if语句,如果getDate()返回的值小于10,则返回一个“0”加上日期,或者如果大于10,则返回日期(因为我们不需要添加前导的0)。该月也是如此
编辑:
忘记了getMonth以0开头,所以添加了+1来解释它。当然,您也可以说d.getMonth()<9:,但我认为使用+1将有助于更容易理解。我将此问题的正确答案包装在一个函数中,该函数可以添加多个前导零,但默认情况下会添加1个零
function zeroFill(nr, depth){
depth = (depth === undefined)? 1 : depth;
var zero = "0";
for (var i = 0; i < depth; ++i) {
zero += "0";
}
return (zero + nr).slice(-(depth + 1));
}
函数零填充(nr,深度){
深度=(深度===未定义)?1:深度;
var zero=“0”;
对于(变量i=0;i
对于仅使用数字且不超过2位的情况,这也是一种方法:
function zeroFill(i) {
return (i < 10 ? '0' : '') + i
}
函数零填充(i){
返回值(i<10?'0':'')+i
}
您可以定义一个“str_pad”函数(如在php中):
我要做的是创建自己的自定义日期帮助器,如下所示:
var-DateHelper={
addDays:函数(aDate,numberOfDays){
aDate.setDate(aDate.getDate()+numberOfDays);//添加numberOfDays
return aDate;//返回日期
},
格式:函数格式(日期){
返回[
(“0”+date.getDate()).slice(-2),//获取日期并用零填充它
(“0”+(date.getMonth()+1)).slice(-2),//获取月份并用零填充它
date.getFullYear()//获取整年
].join(“/”);//将碎片粘在一起
}
}
//有了此帮助程序,您现在只需使用一行可读代码即可:
// ---------------------------------------------------------------------
//1.获取当前日期
//2.增加20天
//3.格式化
//4.输出它
// ---------------------------------------------------------------------
document.body.innerHTML=DateHelper.format(DateHelper.addDays(new Date(),20));
另一个选项,使用内置函数进行填充(但会产生很长的代码!):
另一个是用正则表达式处理字符串:
var myDateString = myDate.toISOString().replace(/T.*/, '').replace(/-/g, '/');
// '2017/06/12'
但请注意,一个人会在开始时显示年份,在结束时显示日期。我找到了最短的方法:
MyDateString.replace(/(^|\D)(\d)(?!\d)/g, '$10$2');
将为所有单个数字添加前导零添加一些填充以允许前导零-其中
var MyDate = new Date();
MyDate.setDate(MyDate.getDate()+10);
var MyDateString = (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate()) + '/' + ((d.getMonth()+1) < 10 ? '0' + (d.getMonth()+1) : (d.getMonth()+1)) + '/' + MyDate.getFullYear();
(MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())
function zeroFill(nr, depth){
depth = (depth === undefined)? 1 : depth;
var zero = "0";
for (var i = 0; i < depth; ++i) {
zero += "0";
}
return (zero + nr).slice(-(depth + 1));
}
function zeroFill(i) {
return (i < 10 ? '0' : '') + i
}
function str_pad(n) {
return String("00" + n).slice(-2);
}
myDateString = myDate.getDate().toLocaleString('en-US', {minimumIntegerDigits: 2})
+ '/' + (myDate.getMonth()+1).toLocaleString('en-US', {minimumIntegerDigits: 2})
+ '/' + myDate.getFullYear();
// '12/06/2017'
var myDateString = myDate.toISOString().replace(/T.*/, '').replace(/-/g, '/');
// '2017/06/12'
MyDateString.replace(/(^|\D)(\d)(?!\d)/g, '$10$2');
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
var d = new Date(my_date);
var dformatted = [(d.getMonth()+1).padLeft(), d.getDate().padLeft(), d.getFullYear()].join('/');
"use strict"
const today = new Date()
const year = today.getFullYear()
const month = `${today.getMonth() + 1}`.padStart(2, "0")
const day = `${today.getDate()}`.padStart(2, "0")
const stringDate = [day, month, year].join("/") // 13/12/2017
"use strict"
let month = "9"
month = month.padStart(2, "0") // "09"
let byte = "00000100"
byte = byte.padStart(8, "0") // "00000100"
var date = new Date(Date.UTC(2012, 1, 1, 3, 0, 0));
var options = { year: 'numeric', month: '2-digit', day: '2-digit' };
console.log(date.toLocaleDateString(undefined,options));
today.toLocaleDateString("default", {year: "numeric", month: "2-digit", day: "2-digit"})
let date = new Date();
let dd = date.getDate();//day of month
let mm = date.getMonth();// month
let yyyy = date.getFullYear();//day of week
if (dd < 10) {//if less then 10 add a leading zero
dd = "0" + dd;
}
if (mm < 10) {
mm = "0" + mm;//if less then 10 add a leading zero
}
var d = new Date();
var datestring = d.getFullYear() + "-" + ("0"+(d.getMonth()+1)).slice(-2) +"-"+("0" + d.getDate()).slice(-2);
Date.prototype.CustomformatDate = function() {
var tmp = new Date(this.valueOf());
var mm = tmp.getMonth() + 1;
if (mm < 10) mm = "0" + mm;
var dd = tmp.getDate();
if (dd < 10) dd = "0" + dd;
return mm + "/" + dd + "/" + tmp.getFullYear();
};
function pad(value) {
return value.tostring().padstart(2, 0);
}
let d = new date();
console.log(d);
console.log(`${d.getfullyear()}-${pad(d.getmonth() + 1)}-${pad(d.getdate())}t${pad(d.gethours())}:${pad(d.getminutes())}:${pad(d.getseconds())}`);
const d = new Date();
const day = `0${d.getDate()}`.slice(-2);
AddZero(val){
// adding 0 if the value is a single digit
return `0${val}`.slice(-2);
}
var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = AddZero(MyDate.getDate()) + '/' + AddZero(MyDate.getMonth() + 1) + '/' + MyDate.getFullYear();
const now = new Date(); // consider 3rd of December 1993
const full = dateFormat(today, "yyyy-mm-dd"); // 1993-12-03
const day = dateFormat(today, "dd"); // 03
const month = dateFormat(today, "mm"); // 12
const year = dateFormat(today, "yyyy"); // 1993