如何在javascript中以格式2009-12-2414:20:57获取当前时间?
我不熟悉javascript中的时间操作 我尝试了如何在javascript中以格式2009-12-2414:20:57获取当前时间?,javascript,Javascript,我不熟悉javascript中的时间操作 我尝试了newdate()以错误格式给出结果: 2009年12月24日星期四14:24:06 GMT+0800 如何以2009-12-24 14:20:57的格式获取时间? <script type="text/javascript"> function formatDate(d){ function pad(n){return n<10 ? '0'+n : n} return [d.getUTCFullYear(),'
newdate()代码>以错误格式给出结果:
2009年12月24日星期四14:24:06 GMT+0800
如何以2009-12-24 14:20:57的格式获取时间?
<script type="text/javascript">
function formatDate(d){
function pad(n){return n<10 ? '0'+n : n}
return [d.getUTCFullYear(),'-',
pad(d.getUTCMonth()+1),'-',
pad(d.getUTCDate()),' ',
pad(d.getUTCHours()),':',
pad(d.getUTCMinutes()),':',
pad(d.getUTCSeconds())].join("");
}
var d = new Date();
var formattedDate = formatDate(d);
</script
函数格式化日期(d){
功能板(n){返回n格式化日期
<script type="text/javascript">
<!--
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
//-->
</script>
打印日期:2009年12月24日
要格式化时间,您可以执行以下操作
<script type="text/javascript">
<!--
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
document.write(curr_hour + ":" + curr_min + ":"
+ curr_sec);
//-->
</script>
打印:8:32:33这是一个不错的
或者你可以这样使用
var dt = new Date();
var timeString = dt.getFullYear() + "-" + dt.getMonth() + "-" + dt.getDate() + " " + dt.getHours() + ":" + dt.getMinutes() +":" + dt.getSeconds()
使用找到的日期片段,根据您的喜好格式化
即
目前没有跨浏览器的Date.format()方法。有些工具包(如Ext)有一个但不是全部(我很确定jQuery没有)。如果您需要灵活性,可以在web上找到几种这样的方法。如果您希望始终使用相同的格式,那么:
var now = new Date();
var pretty = [
now.getFullYear(),
'-',
now.getMonth() + 1,
'-',
now.getDate(),
' ',
now.getHours(),
':',
now.getMinutes(),
':',
now.getSeconds()
].join('');
我的Java SimpleDataFormat格式方法的JavaScript实现可能会帮助您:是否还要填充小于10的字段?更好的示例是一些小于10的值。请仔细考虑是否要在本地时间或时区(或“Z”)中填充。ES5提供了toISOString()方法,目前在某些浏览器中可用。
var now = new Date();
var pretty = [
now.getFullYear(),
'-',
now.getMonth() + 1,
'-',
now.getDate(),
' ',
now.getHours(),
':',
now.getMinutes(),
':',
now.getSeconds()
].join('');