gpt4 book ai didi

javascript - 在javascript中将日期字符串转换为dd/mm/yy

转载 作者:行者123 更新时间:2023-11-29 19:11:27 25 4
gpt4 key购买 nike

我要转换

Tue Jul 12 2016 00:00:00 GMT+0100 (BST)

进入

12/07/2016

假设我有 d = Tue Jul 12 2016 00:00:00 GMT+0100 (BST)。我试过了

var a = d.getDate()+"/"+(d.getMonth()+1)+"/"+d.getFullYear();

但后来我得到 12/7/2016 而不是 12/07/2016

我可以

if(d.getMonth()<10){
var a = d.getDate()+"/0"+(d.getMonth()+1)+"/"+d.getFullYear();

但我不喜欢那样,而且当一天少于 10 时我也会遇到同样的问题。什么是获得我想要的格式的最佳方法。我只需要它作为在 View 中显示的字符串。

最佳答案

这个呢

var month = 7; // july (months are base 0)
var day = 12;
var year = 2016;
var d = new Date(year,month-1,day);

var a = pad(d.getDate(),2)+"/"+pad(d.getMonth()+1,2)+"/"+d.getFullYear();
console.log(a)


function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}

使用了 How to output integers with leading zeros in JavaScript 中的填充函数

您可能还想查看 http://momentjs.com/到“在 JavaScript 中解析、验证、操作和显示日期。”

这是另一个填充函数(我用过很多)

var month = 7; // july (months are base 0)
var day = 12;
var year = 2016;
var d = new Date(year,month-1,day);

var a = pad(d.getDate(),2)+"/"+pad(d.getMonth()+1,2)+"/"+d.getFullYear();
console.log(a)

/**
* Returns a zero-padded string of length characters
* When the number is more than the length, the number is returned
* in its full length (longer than the specified length)
* @param {Number} number The number to be padded
* @param {Number=2} length
* @returns {String} the padded String or the number if longer than specified length
*/
function pad(number, length) {
if (length === undefined) {
length = 2;
}
var missing = length - digits(number);
if (missing < 0) return number.toString();
return Array(missing + 1).join("0") + number.toString();
}

/**
* Utility function to return the number of digits of a number
* @param {Number} int the number for which to get the #digits
* @returns {Number} the number of digits
*/
function digits(int) {
return Math.floor(Math.log(int) / Math.LN10 + 1);
}

关于javascript - 在javascript中将日期字符串转换为dd/mm/yy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38592698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com