是否有可能确定,与纯Javascript,什么日期时间格式用户配置在他的操作系统(Windows, Linux, MAC OS等)?
提前感谢。
编辑:我知道关于方法toLocaleString(),但这并不能帮助我获得格式,客户端已配置在他的本地机器上。
我用纯javascript写了一些在IE/Firefox/Chrome中工作的东西。它会输出MM/DD/YYYY或DD/MM/YYYY,…取决于toLocalDateString()。
不能在Safari上工作,但是new Date(). tolocaldatestring()也不能。
这是一个jsFiddle
//Create a known date string
var y = new Date(2013, 9, 25);
var lds = y.toLocaleDateString();
//search for the position of the year, day, and month
var yPosi = lds.search("2013");
var dPosi = lds.search("25");
var mPosi = lds.search("10");
//Sometimes the month is displayed by the month name so guess where it is
if(mPosi == -1)
{
mPosi = lds.search("9");
if(mPosi == -1)
{
//if the year and day are not first then maybe month is first
if(yPosi != 0 && dPosi != 0)
{
mPosi = 0;
}
//if year and day are not last then maybe month is last
else if((yPosi+4 < lds.length) && (dPosi+2 < lds.length)){
mPosi = Infinity;
}
//otherwist is in the middle
else if(yPosi < dPosi){
mPosi = ((dPosi - yPosi)/2) + yPosi;
}else if(dPosi < yPosi){
mPosi = ((yPosi - dPosi)/2) + dPosi;
}
}
}
var formatString="";
var order = [yPosi, dPosi, mPosi];
order.sort(function(a,b){return a-b});
for(i=0; i < order.length; i++)
{
if(order[i] == yPosi)
{
formatString += "YYYY/";
}else if(order[i] == dPosi){
formatString += "DD/";
}else if(order[i] == mPosi){
formatString += "MM/";
}
}
formatString = formatString.substring(0, formatString.length-1);
$('#timeformat').html(formatString+" "+lds);
我有个主意,也许可行,也许不可行。
创建一个所有元素都不相同的日期,如February 18 1999 at 13:45,使用toLocaleString()
,然后根据它们不同的值识别元素。
可能有点复杂,我没有任何代码可以帮助它,但这是一个想法,也许你可以利用它。
编辑:这里有一些代码:
var d = new Date(1999,1,18,13,45,0).toLocaleString();
document.write("<p>String: "+d+"</p>");
var f = d
.replace(/1999/,"%Y")
.replace(/99/,"%y")
.replace(/F[^ ]{3,}/i,"%M")
.replace(/F[^ ]+/i,"%m")
.replace(/PM/,"%A")
.replace(/pm/,"%a")
.replace(/18[^ ]+/,"%d%S") // day number with suffix
.replace(/18/,"%d")
.replace(/13/,"%H")
.replace(/1/,"%h")
.replace(/45/,"%i")
.replace(/00/,"%s");
// optionally add something to detect the day of the week (Thursday, here)
document.write("<p>Format: "+f+"</p>");
输出:String: 18 February 1999 13:45:00
Format: %d %M %Y %H:%i:%s
像这样?
<script type="text/javascript">
var d=new Date();
document.write("Original form: ");
document.write(d + "<br />");
document.write("Formatted form: ");
document.write(d.toLocaleString());
//calculate change of the 2 dates
</script>