Javascript 添加前导零至今
我创建了这个脚本,以 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;
如果
if (MyDate.getDate <10)get.Date = '0' + getDate;
有人可以告诉我在脚本中的何处插入这些内容,我将非常感激。
I've created this script to calculate the date for 10 days in advance in the format of dd/mm/yyyy:
var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = MyDate.getDate() + '/' + (MyDate.getMonth()+1) + '/' + MyDate.getFullYear();
I need to have the date appear with leading zeroes on the day and month component by way of adding these rules to the script. I can't seem to get it to work.
if (MyDate.getMonth < 10)getMonth = '0' + getMonth;
and
if (MyDate.getDate <10)get.Date = '0' + getDate;
If someone could show me where to insert these into the script I would be really appreciative.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
您可以定义一个“str_pad”函数(如在 php 中):
You can define a "str_pad" function (as in php):
我找到了最短的方法来做到这一点:
将前导零添加到所有孤独的个位数
I found the shorterst way to do this:
will add leading zeros to all lonely, single digits
//使用中:
//in use:
现在您还可以使用 String.prototype.padStart< /a> 以快速、简单的方式实现目标
可用性可以在 caniuse 进行评估
检查
适用于旧浏览器的 Polyfill
Nowadays you can also utilize String.prototype.padStart to reach the goal in quick and easy way
The availability can be assessed at caniuse
Check
Polyfill for old browsers
还有另一种方法可以解决这个问题,那就是在 JavaScript 中使用
slice
。datestring
返回格式符合您预期的日期:2019-09-01另一种方法是使用
dateformat
库:https://github.com/felixge/node-dateformatThere is another approach to solve this problem, using
slice
in JavaScript.the
datestring
return date with format as you expect: 2019-09-01another approach is using
dateformat
library: https://github.com/felixge/node-dateformat您可以使用三元运算符来格式化日期,就像“if”语句一样。
例如:
So
类似于 if 语句,如果 getDate() 返回一个小于 10 的值,则返回 '0' + Date,否则返回大于 10 的日期(因为我们不需要添加前导 0)。这个月也一样。
编辑:
忘记了 getMonth 是从 0 开始的,所以添加了 +1 来解释它。当然你也可以直接说 d.getMonth() < 9 :但我认为使用 +1 有助于使其更容易理解。
You could use ternary operator to format the date like an "if" statement.
For example:
So
would be similar to an if statement, where if the getDate() returns a value less than 10, then return a '0' + the Date, or else return the date if greater than 10 (since we do not need to add the leading 0). Same for the month.
Edit:
Forgot that getMonth starts with 0, so added the +1 to account for it. Of course you could also just say d.getMonth() < 9 :, but I figured using the +1 would help make it easier to understand.
您可以提供选项作为参数来格式化日期。第一个参数用于您可能不需要的区域设置,第二个参数用于选项。
欲了解更多信息,请访问
https://developer.mozilla.org/ en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
You can provide options as a parameter to format date. First parameter is for locale which you might not need and second is for options.
For more info visit
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
我将这个问题的正确答案包装在一个函数中,该函数可以添加多个前导零,但默认添加 1 个零。
对于仅处理数字且不超过 2 位数字,这也是一种方法:
I wrapped the correct answer of this question in a function that can add multiple leading zero's but defaults to adding 1 zero.
for working with numbers only and not more than 2 digits, this is also an approach:
添加到 @modiX 答案,这就是有效的...不要将其保留为空
Adding on to @modiX answer, this is what works...DO NOT LEAVE THAT as empty
另一种选择是使用内置函数进行填充(但会导致代码相当长!):
另一种选择是使用正则表达式操作字符串:
但请注意,它会在开始时显示年份 > 以及结束的日期。
Another option, using a built-in function to do the padding (but resulting in quite long code!):
And another, manipulating strings with regular expressions:
But be aware that one will show the year at the start and the day at the end.
这是如何处理这种情况的非常简单的示例。
Here is very simple example how you can handle this situation.
我认为这个解决方案更容易并且容易记住:
I think this solution is easier and can be easily remembered:
我要做的是创建我自己的自定义日期助手,如下所示:
(另请参阅这个小提琴)
What I would do, is create my own custom Date helper that looks like this :
(see also this Fiddle)
正如@John Henckel建议的那样,开始使用 toISOString () 方法使事情变得更容易
As @John Henckel suggests, starting using the toISOString() method makes things easier
尝试这个基本功能,不需要库
try this for a basic function, no libraries required
您可以使用 String.slice() 提取字符串的一部分并将其作为新字符串返回,而不修改原始字符串:
或者您也可以使用库,例如 Moment.js 格式化日期:
You can use String.slice() which extracts a section of a string and returns it as a new string, without modifying the original string:
Or you can also use a lib such as Moment.js to format the date:
您可以简单地使用:
因此可以创建一个函数,如下所示:
您的新代码:
You could simply use :
So a function could be created like :
Your new code :
toISOString 可以获得前导 0
输出将类似于:2021-06-09T12:14:27.000Z
toISOString can get leading 0
output will be similar to this : 2021-06-09T12:14:27.000Z
我能想到的最短版本:
Shortest version I can think of:
以下目标是提取配置、挂钩到 Date.protoype 并应用配置。
我使用
Array
来存储时间块,当我将push()
this
作为Date
对象时,它返回我要迭代的长度。完成后,我可以在return
值上使用join
。这似乎工作得很快:0.016ms
演示: http://jsfiddle.net/主动/U4MZ3/
The following aims to extract configuration, hook into
Date.protoype
and apply configuration.I've used an
Array
to store time chunks and when Ipush()
this
as aDate
object, it returns me the length to iterate. When I'm done, I can usejoin
on thereturn
value.This seems to work pretty fast: 0.016ms
demo: http://jsfiddle.net/tive/U4MZ3/
添加一些填充以允许在需要时添加前导零,并使用您选择的分隔符作为字符串进行连接。
Add some padding to allow a leading zero - where needed - and concatenate using your delimiter of choice as string.
试试这个: http://jsfiddle.net/xA5B7/
编辑:
解释一下,
.slice(-2)
为我们提供了字符串的最后两个字符。因此,无论如何,我们都可以将
"0"
添加到日期或月份,并只要求最后两个,因为这些始终是我们想要的两个。因此,如果
MyDate.getMonth()
返回9
,它将是:因此添加
.slice(-2)
就可以得到最后一个两个字符,即:但是如果
MyDate.getMonth()
返回10
,它将是:所以添加
.slice(-2)
给我们最后两个字符,或者:Try this: http://jsfiddle.net/xA5B7/
EDIT:
To explain,
.slice(-2)
gives us the last two characters of the string.So no matter what, we can add
"0"
to the day or month, and just ask for the last two since those are always the two we want.So if the
MyDate.getMonth()
returns9
, it will be:so adding
.slice(-2)
on that gives us the last two characters which is:But if
MyDate.getMonth()
returns10
, it will be:so adding
.slice(-2)
gives us the last two characters, or:现代方法
新的现代方法是使用
toLocaleDateString
,因为它不仅允许您使用正确的本地化来格式化日期,甚至还可以传递格式选项以实现所需的结果:或者使用 Temporal 对象(仍在提案中,caniuse):
当您使用
undefined
作为第一个参数时,它将检测浏览器语言。或者,您也可以在年份选项上使用2 位
。性能
如果您打算格式化大量日期,则应考虑使用
Intl.DateTimeFormat
改为:格式化程序与日期和时间对象兼容。
历史日期
与 Temporal 构造函数不同,0 到 99 之间的年份在 Date 构造函数中将被解释为 20 世纪年份。为了防止这种情况,请像这样初始化日期:
这对于 Temporal 对象来说不是必需的,但低于 1000 的年份在所有情况下都不会包含前导零,因为格式化程序(为 Date 和 Temporal API 共享)不支持
4 位数字
完全格式化。在这种情况下,您必须手动格式化(见下文)。对于 ISO 8601 格式
如果您想获取
YYYY-MM-DD
格式 (ISO 8601) 的日期,解决方案看起来会有所不同:您输入的日期应采用 UTC 格式,否则
toISOString()
将为您解决该问题。这是通过使用Date.UTC
来完成的,如上所示。ISO 8601 格式的历史日期
与 Temporal 构造函数不同,0 到 99 之间的年份在 Date 构造函数中将被解释为 20 世纪年份。为了防止这种情况,请像这样初始化日期以用于 ISO 8601 格式:
请注意,日期在 1000 年之前或 9999 年之后的 Temporal 对象的 ISO 格式将具有 与旧版 Date API 相比,格式不同。建议在所有情况下回退到自定义格式以强制使用 4 位数年份。
年份的自定义 4 位格式
遗憾的是,格式化程序不支持年份的前导零。没有
4 位
选项。这也适用于 Temporal 对象,因为它们确实共享相同的格式化程序。幸运的是,Date API 的 ISO 格式将始终显示至少 4 位数字的年份,但 Temporal 对象不会。因此,至少对于 Date API,您可以使用 ISO 8601 格式方法的一部分,使用手动格式化方法来格式化 1000 年之前的带有前导零的历史日期:
对于 Temporal 对象,需要不同的路由,因为
ISOYearString
对于 1000 年之前和 9999 年之后的日期,格式会有所不同,如前所述:其他
对于日期和时间 API,还有
toLocaleTimeString
,它允许您本地化和格式化日期的时间。The modern way
The new modern way to do this is to use
toLocaleDateString
, because it allows you not only to format a date with proper localization, but even to pass format options to achieve the desired result:Or using a Temporal object (still in proposal, caniuse):
When you use
undefined
as the first argument it will detect the browser language, instead. Alternatively, you can use2-digit
on the year option, too.Performance
If you plan to format a lot of dates, you should consider using
Intl.DateTimeFormat
instead:The formatter is compatible with Date and Temporal objects.
Historical dates
Unlike in the Temporal constructor years between 0 and 99 will be interpreted as 20th century years on the Date constructor. To prevent this, initialize the date like so:
This is not required for Temporal objects, but years below 1000 will not contain leading zeros in all cases, because the formatter (that is shared for the Date and Temporal API) does not support
4-digit
formatting at all. In this case you have to do manual formatting (see below).For the ISO 8601 format
If you want to get your date in the
YYYY-MM-DD
format (ISO 8601), the solution looks different:Your input date should be in the UTC format or
toISOString()
will fix that for you. This is done by usingDate.UTC
as shown above.Historical dates for the ISO 8601 format
Unlike in the Temporal constructor years between 0 and 99 will be interpreted as 20th century years on the Date constructor. To prevent this, initialize the date like so to be used for the ISO 8601 format:
Note that the ISO format for Temporal objects with dates before the year 1000 or after the year 9999 will have a different formatting compared to the legacy Date API. It is recommend to fallback to custom formatting to enforce 4 digit years in all circumstances.
Custom 4-digit formatting on the year
Sadly, the formatter doesn't support leading zeros on the year. There is no
4-digit
option. This will remain for Temporal objects as well, because they do share the same formatter.Fortunately, the ISO format of the Date API will always display at least 4 digits on the year, although Temporal objects do not. So at least for the Date API you can format historical dates before the year 1000 with leading zeros by falling back to a manual formatting approach using part of the ISO 8601 format method:
For a Temporal object a different route is necessary, since the
ISOYearString
will be formatted differently for dates before the year 1000 and after the year 9999 as mentioned before:Miscellaneous
For the Date and Temporal API there is also
toLocaleTimeString
, that allows you to localize and format the time of a date.以下是日期对象文档 在 Mozilla 开发者网络上使用自定义“pad”函数,而无需扩展 Javascript 的 Number 原型。他们作为示例给出的方便功能是
下面是它在上下文中的使用情况。
Here is an example from the Date object docs on the Mozilla Developer Network using a custom "pad" function, without having to extend Javascript's Number prototype. The handy function they give as an example is
And below is it being used in context.
对于来自未来的人们(ECMAScript 2017 及更高版本)
解决方案
解释
String.prototype.padStart(targetLength[, padString])
在String.prototypepadString
code> target,以便目标的新长度为targetLength
。例子
For you people from the future (ECMAScript 2017 and beyond)
Solution
Explaination
the
String.prototype.padStart(targetLength[, padString])
adds as many as possiblepadString
in theString.prototype
target so that the new length of the target istargetLength
.Example