如何在JavaScript中将7格式化为'07'? [英] How do I format 7 as '07' in string in JavaScript?

查看:88
本文介绍了如何在JavaScript中将7格式化为'07'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一天,一个月和一年的JavaScript。我需要我的一天是两位数,我的月份也是2位数,年份是4位数。

I have JavaScript day, month and year. I need my day to be in 2 digits, my months also to be in 2 digits and year in 4 digits.

例如。如果是月份是 7 它应该给我字符串 '07'。如果它是 12 那么它应该返回 '12'

Eg. If month is 7 it should give me string as '07'. If it is 12 then it should return '12'.

我谷歌,但我只找到 toFixed toPrecision ,两者都有不同的功能。如何格式化?

I google for it but I only found toFixed and toPrecision, both of which have different functions. How do I format it?

推荐答案

var newmonth = month < 10 ? '0' + month : month; // if month is number
                                                 // else use parseInt(month, 10)

你也可以制作一般用途的功能:

You can also make a function for general use:

function formatting(target) {
  return target < 10 ? '0' + target : target;
}

您可以将上述方法用于月份和日期。

You can use above approach for month and days.

并且要获得4位数年份,您可以使用 .getFullYear()

and to get a 4 digits year you can use .getFullYear()

这篇关于如何在JavaScript中将7格式化为'07'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆