如何检测用户的区域设置日期和时间格式 [英] How to detect the user's locale date and time format

查看:109
本文介绍了如何检测用户的区域设置日期和时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有可能使用纯粹的Javascript来确定用户在他的操作系统(Windows,Linux,MAC OS等)上配置的日期时间 FORMAT

Is there a possibility to determine, with pure Javascript, what date time FORMAT has user configured on his operating system (Windows, Linux, MAC OS, etc.)?

提前感谢

编辑:我知道方法toLocaleString(),但这并不能帮助我得到<

I know about the method toLocaleString(), but this isn't help me to get the format that client has configured on his local machine.

推荐答案

我写了一些纯粹的javascript,它的作品在IE / Firefox / Chrome。它将放出MM / DD / YYYY或DD / MM / YYYY,取决于toLocalDateString()。

I wrote something in pure javascript that works in IE/Firefox/Chrome. It will out put MM/DD/YYYY or DD/MM/YYYY,... depending in toLocalDateString().

没有在Safari上工作,但新的Date() .toLocalDateString()也没有。

Did not work on Safari but new Date().toLocalDateString() did not either.

这是一个 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);

这篇关于如何检测用户的区域设置日期和时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆