javascript 如何为 toLocaleString 设置通用格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33057291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:04:19  来源:igfitidea点击:

How to set common format for toLocaleString?

javascriptangularjs

提问by Xakerok

I use JS function toLocaleStringfor date formatting. How can I set one common format for all clients like:

我使用 JS 函数toLocaleString进行日期格式化。如何为所有客户端设置一种通用格式,例如:

2015-10-29 20:00:00

That I do parsong at PHP by -

我在 PHP 做 parsong -

采纳答案by David Li

I think you would have to manually parse it into that format, which actually isn't too bad. What Date.toLocaleString() returns is a format of:

我认为您必须手动将其解析为该格式,这实际上还不错。Date.toLocaleString() 返回的是以下格式:

MM/DD/YYYY, HH:MM:SS

Here's my code snippet to help you out:

这是我的代码片段,可以帮助您:

// Parse our locale string to [date, time]
var date = new Date().toLocaleString('en-US',{hour12:false}).split(" ");

// Now we can access our time at date[1], and monthdayyear @ date[0]
var time = date[1];
var mdy = date[0];

// We then parse  the mdy into parts
mdy = mdy.split('/');
var month = parseInt(mdy[0]);
var day = parseInt(mdy[1]);
var year = parseInt(mdy[2]);

// Putting it all together
var formattedDate = year + '-' + month + '-' + day + ' ' + time;

回答by Anonymous0day

before doing what i provide please read thisand this

在做我提供的之前,请阅读这个这个

var el = document.getElementById('dbg');
var log = function(val){el.innerHTML+='<div><pre>'+val+'</pre></div>'};
var pad = function(val){ return ('00' + val).slice(-2)};

Date.prototype.myFormattedString = function(){
  return this.getFullYear()     + '-' + 
        pad( (this.getMonth() + 1) )   + '-' + 
        pad( this.getDate() )          + ' ' + 
        pad( this.getHours() )         + ':' + 
        pad( this.getMinutes() )       + ':' +
        pad( this.getSeconds() )
    ;
}

var curDate = new Date();

log( curDate )
log( curDate.toLocaleString() )
log( curDate.myFormattedString() )
<div id='dbg'></div>