本文介绍了从使用toLocaleString()返回的日期中删除“EDT”的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我比较新的javascript,所以这可能是一个非常简单的问题。有没有一个简单的方法来停止'EDT'打印后返回与LocaleString? 谢谢!解决方案没有办法确定什么 toLocaleString 将返回;您当然不能保证 EDT 将显示在运行它的每台机器上,更不用说任何时区的指示。 从Mozilla的开发人员网络:可能解决办法是使用 toLocaleDateString构建自定义日期字符串 和 toLocaleTimeString 。 //有一些这样的效果: var d = new Date(); console.log(d.toLocaleDateString()++ d.toLocaleTimeString()); 这通常不会在其输出中包含时区,但即使这不是完美的您不能知道输出的确切格式是什么。 因此,最佳解决方案是使用自定义日期格式化功能: //将前导零添加到小于10 [000 ...]的数字函数padZ(num,n){n = n || 1; //默认假设为10 ^ 1 return num } 函数formattedDate(d){ var day = d.getDate(); var month = d.getMonth()+ 1; //注意`+ 1` - 从零开始的月份。 var year = d.getFullYear(); var hour = d.getHours(); var min = d.getMinutes(); var sec = d.getSeconds(); 返回月份+/+天+/+年++小时+:+ padZ(最小)+:+ padZ(秒) } 要深入了解可用的日期方法,请查看 日期 。 I'm relatively new to javascript, so this may be a really simple question. Is there an easy way to stop 'EDT' from printing after a date returned with toLocaleString?Thanks! 解决方案 There is no way to be certain what toLocaleString will return; you certainly couldn't guarantee EDT would show up on every machine that runs it, let alone any indication of timezone.From Mozilla's developer network:One possible workaround would be to construct a custom date string using toLocaleDateString and toLocaleTimeString.// Something to this effect:var d = new Date();console.log(d.toLocaleDateString() + " " + d.toLocaleTimeString());This generally wouldn't include the time zone in its output, but even this isn't perfect as you can't know what the exact format of the output would be.Thus, the best solution would be to use a custom date-formatting function:// Add leading-zeros to numbers less than 10[000...]function padZ(num, n) { n = n || 1; // Default assume 10^1 return num < Math.pow(10, n) ? "0" + num : num;}function formattedDate(d) { var day = d.getDate(); var month = d.getMonth() + 1; // Note the `+ 1` -- months start at zero. var year = d.getFullYear(); var hour = d.getHours(); var min = d.getMinutes(); var sec = d.getSeconds(); return month+"/"+day+"/"+year+" "+hour+":"+padZ(min)+":"+padZ(sec);}For an in-depth look at the available Date methods, check out Date on the MDN. 这篇关于从使用toLocaleString()返回的日期中删除“EDT”的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
11-01 20:09